我有一个案例,我在列表中动态创建组件(刷新很多)并使用像这样的ngSwitch:
<div *ngFor='let item of items'> <div [ngSwitch]="item.view"> <view-one *ngSwitchCase="'one'"></view-one> <view-two *ngSwitchCase="'two'"></view-two> <view-three *ngSwitchCase="'three'"></view-three> </div> </div>
我见过人们动态创建组件,但api已经改变了很多次,很难知道什么是正确的.似乎ViewContainerRef.createComponent()可能是另一种选择?
解决方法
我更喜欢createComponent()而不是ngSwitch,因为我认为它更容易测试和扩展.我还没有看到任何表现不足.
这是我当前方法的简化形式:
@Component({ selector: "my-item",template: ` <div #placeholder></div> ` }) export class MyItemComponent implements AfterViewInit { @Input() item: any; @ViewChild("placeholder",{read: ViewContainerRef}) placeholderRef: ViewContainerRef; constructor( private componentFactoryResolver: ComponentFactoryResolver) { } ngAfterViewInit() { switch(this.item.view) { case "one": this.loadItem(OneItemComponent); case "two": this.loadItem(TwoItemComponent); default: throw new Error("Unknown item!"); } } private loadItem(component: Type<any>) { const factory = this.componentFactoryResolver.resolveComponentFactory(component); const componentRef = this.placeholderRef.createComponent(factory); componentRef.instance.item = this.item; componentRef.changeDetectorRef.detectChanges(); } }
现在您可以通过以下方式使用它:
<my-item *ngFor="let item of items" [item]="item"></my-item>