【问题标题】:Angular create Selector Tag <app-component> using variable or loopAngular 使用变量或循环创建选择器标记 <app-component>
【发布时间】:2018-09-14 03:54:54
【问题描述】:

我需要使用一个变量来制作我的 app.component.html 的 Selector Tag。

假设变量名是:componentVar:string

我需要我的 app.component.html:

&lt;componentVar&gt;&lt;/componentVar&gt;&lt;app-componentVar&gt;&lt;/app-componentVar&gt;

【问题讨论】:

  • 您想动态创建组件?为什么你希望你的组件选择器以变量值命名?
  • 我在 app-component.html 中附加了很多组件,我必须在其中设置条件以显示隐藏它们。因此,如果可以使用变量创建选择器标签,那么我将使用循环创建它们并使用条件。
  • *ngIf 没问题,但我需要使用动态值命名选择器。

标签: javascript angular typescript frontend


【解决方案1】:

您可以像这样在 ViewcontainerRef 中动态创建组件:

https://stackblitz.com/edit/angular-4asbmc

(不要忘记在你的应用模块的 entryComponents 中添加你想要动态注入的组件)

一旦您能够插入组件,您就应该能够管理哪些组件必须插入到您的 with 条件中。

编辑

您可以迭代一个可能如下所示的组件数组:

let componentArray = [HeaderComponent, BannerComponent, FooterComponent];

然后遍历这个数组,调用将组件插入到视图容器引用中的方法。

  createComponent(component) {
    const factory = this.factoryResolver.resolveComponentFactory(component);
    const componentRef = factory.create(yourViewContainerRef.parentInjector);
    yourViewContainerRef.insert(componentRef.hostView);
  }

虽然从你的应用组件 html 模板中调用你的组件会更容易,并且在你的模板中有这样的东西:

<app-header *ngIf="yourConditions..."></app-header>
<app-banner *ngIf="otherConditions..."></app-banner>
<!-- and so on.... -->

【讨论】:

  • 您所解释的内容将起作用,但与我的预期不同。我不能使用它,因为我有许多要放置的组件。我需要一个简单的解决方案来从如下所示的选择器名称数组中创建选择器标签。 app.component.ts 中的选择器数组:[ "app-header", "app-banner", "app-content", "app-footer"] app.component.html 应该像: app-header> 我需要使用上面的数组来渲染上面的html。
  • 我更新了 stackblitz 以向您展示如何创建所需的组件。基本上你应该像这样创建一个组件数组:let componentArray = [HeaderComponent, BannerComponent, ...]; componentArray.forEach(component =&gt; createComponent(component)); createComponent 方法几乎与使用的函数相同,除了它现在有一个参数,即应该创建并插入到你的 ng-template 中的组件类型跨度>
  • 好的,让我试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 2016-08-27
相关资源
最近更新 更多