Angular 2:ngSwitch或ViewContainerRef.createComponent
发布时间:2020-12-17 17:02:18 所属栏目:安全 来源:网络整理
导读:我有一个案例,我在列表中动态创建组件(刷新很多)并使用像这样的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="'thre
我有一个案例,我在列表中动态创建组件(刷新很多)并使用像这样的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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容