【问题标题】:Binding Angular 2 components with a list of selectors string format使用选择器字符串格式列表绑定 Angular 2 组件
【发布时间】:2023-03-14 20:07:01
【问题描述】:

我在 Angular 2 中定义了一个列表小部件组件选择器。当我在 HTML 文件中键入 <app-xxx-widget></app-xxx-widget> 时仍然可以。问题是我有一个字符串格式的组件选择器数组,当我绑定{{ widgetTag }}(使用*ngFor="let widgetTag of widgetTagList")时,浏览器只会将widgetTag 理解为文本,而不是Angular 组件。我该如何解决这个问题?
我认为在这种情况下是不可能的

【问题讨论】:

  • 你能提供你的代码吗?
  • {{ widgetTag }}
    跨度>
  • 你容易理解吗?如果没有,我会解释更多..

标签: javascript angular binding


【解决方案1】:

您可以动态创建它们,这有点棘手但完全可行。

一些例子:

http://blog.rangle.io/dynamically-creating-components-with-angular-2/

https://medium.com/@tudorgergely/injecting-components-dynamically-in-angular-2-3d36594d49a0

https://angular.io/guide/dynamic-component-loader

加载 1 个组件的基本示例:

  • 注入InjectorNgModuleFactoryLoader
  • 在模板中添加一个容器元素(例如<div #componentReference></div>
  • 添加一个组件引用元素以保存对已创建组件的引用
  • 从它的工厂创建一个组件

    public component: any;
    @ViewChild('componentReference') componentReference: any;
    
    public createComponent(module: string, component: string) {
    
    this.loader.load(module).then(
    
      (f: NgModuleFactory<any>) => {
    
        const moduleRef = f.create(this.injector);   
    
        (<any>moduleRef.componentFactoryResolver)._factories.forEach(
          (cF) => {
            if (cF.componentType.name === component) {
    
              const fac = moduleRef.componentFactoryResolver.resolveComponentFactory(cF.componentType);
              this.componentReference = this.component.createComponent(fac);
            }
          }
        );
      });
    

    }

这个例子是用组件.name 制作的,但可以很容易地更改为使用选择器,但是你必须自己弄清楚。 确保所需的组件位于您的模块中 entryComponents

【讨论】:

猜你喜欢
  • 2020-03-30
  • 1970-01-01
  • 2016-11-12
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 2018-02-28
  • 1970-01-01
相关资源
最近更新 更多