【发布时间】:2016-12-14 16:34:05
【问题描述】:
我想知道创建动态组件的最佳方式(性能)是什么。 我尝试了两种方法,但无法确定应该使用哪一种。
在我的 component.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;
}
}
}
这是一个简单的例子,在我的应用程序中我有大量的动态组件。
提前感谢您的回答。
【问题讨论】:
-
在我的第二个例子中,很酷的是我可以在我的 childComponent 上有一个实例,我可以轻松地操作实例和调用方法。在我看来,这更像是面向对象的方式。
标签: angular angular2-components