Angular 2:ngSwitch或ViewContainerRef.createComponent

前端之家收集整理的这篇文章主要介绍了Angular 2:ngSwitch或ViewContainerRef.createComponent前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个案例,我在列表中动态创建组件(刷新很多)并使用像这样的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>

猜你在找的Angularjs相关文章