gpt4 book ai didi

Angular 2 : ngSwitch or ViewContainerRef. createComponent

转载 作者:太空狗 更新时间:2023-10-29 18:08:55 34 4
gpt4 key购买 nike

我有一个案例,我在列表中动态创建组件(经常刷新)并像这样使用 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>

关于 Angular 2 : ngSwitch or ViewContainerRef. createComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794358/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com