我希望了解创建动态组件的最佳方式(性能)。我尝试过两种方法,但无法确定应该使用哪一种。
在我的组件.html容器中使用ng-switch
@Component({
selector: 'app-component-container',
template: `<div [ngSwitch]="typeComponent">
<app-component-one *ngSwitchCase="1" [value]="someValue"></app-component-one>
<app-component-two *ngSwitchCase="2" [value]="someValue"></app-component-two>
<app-component-three *ngSwitchCase="3" [value]="someValue"></app-component-three>
</div>`
})
export class ContainerComponent implements OnInit {
private typeComponent: number;
private someValue: string;
constructor() {
this.typeComponent = 2;
this.someValue = "Hello";
}
ngOnInit() {
}
}
或者在我的component.ts容器中使用组件构建器
@Component({
selector: 'app-component-container',
template: '<div #container></div>'
})
export class ContainerComponent implements OnInit {
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
private typeComponent: number;
private someValue: string;
constructor(private _resolver: ComponentFactoryResolver) {
this.typeComponent = 2;
this.someValue = "Hello";
}
ngOnInit() {
let childComponent: ComponentRef<any> = null;
switch (this.typeComponent) {
case 1:
childComponent = this.container.createComponent<ChildComponentOne>(this._resolver.resolveComponentFactory(ChildComponentOne));
break;
case 2:
childComponent = this.container.createComponent<ChildComponentTwo>(this._resolver.resolveComponentFactory(ChildComponentTwo));
break;
case 3:
childComponent = this.container.createComponent<ChildComponentThree>(this._resolver.resolveComponentFactory(ChildComponentThree));
break;
}
if (childComponent != null) {
childComponent.instance.value = this.someValue;
}
}
}
这只是一个简单的例子,在我的应用程序中有大量嵌套的动态组件。非常感谢各位的回答。