【问题标题】:Dynamically switch component based on some predefined array by using ngFor使用 ngFor 基于一些预定义的数组动态切换组件
【发布时间】:2018-04-16 00:41:34
【问题描述】:

我想根据一些预定义的数组数据分别为每个选项卡分配组件。我试图通过在 html 模板中使用 ngFor 迭代来做到这一点。 但是目前我无法通过迭代器将组件指定为 div 。有没有办法解决这个问题?

以下是我想要做的。

【问题讨论】:

  • 在 mat-tab 里面你需要渲染 test1 和 test2 组件。您可以使用 ngFor 索引或自定义指令引用 viewContainerRef 我们可以实现它link

标签: angular


【解决方案1】:

您可以通过自定义指令来实现这一点,以引用 viewContainerRef

html

<mat-card>
  <mat-card-content>
    <mat-tab-group>
      <mat-tab *ngFor="let item of menulist[0].menus" [label]="item.label">
        <ng-container add-comp [comp]="item.component"></ng-container>
      </mat-tab>
    </mat-tab-group>
  </mat-card-content>
</mat-card> 

指令

import { Directive, Type, ViewContainerRef, Input, ComponentFactoryResolver } from '@angular/core';

@Directive({
  selector: '[add-comp]',
})
export class AddDirective {

  @Input('comp') comp : Type<any>
  constructor(public viewContainerRef: ViewContainerRef,
  public componentFactoryResolver:ComponentFactoryResolver) {

   }

   ngAfterViewInit(){
     let componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.comp);
     this.viewContainerRef.clear();
     this.viewContainerRef.createComponent(componentFactory);
   }
}

请参考在组件和 main.ts 文件中所做的更改的堆栈闪电战链接 https://stackblitz.com/edit/angular-ranet6-m9pp7j?file=app%2FaddComp.directive.ts

【讨论】:

  • 谢谢!这就是我想做的。我的代码合并了您的代码也按我的预期工作。
  • 工作正常,但使用 ngOnInit() 而不是 ngAfterViewInit(),否则会导致 ExpressionChangedAfterItHasBeenCheckedError
猜你喜欢
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2020-09-06
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2021-05-23
相关资源
最近更新 更多