什么是更好的?使用 ngFor 或 ViewContainerRef 动态创建组件?有什么区别?
例如,如果我有一个按钮来创建一个新元素,每次按下它都会生成一个新组件。
1)第一个选项如下
items: number[] = [];
addItem() {
this.items.push(1);
}
<my-component *ngFor="let item of items"></my-component>
2)第二个选项
@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;
index: number = 0;
componentsReferences = [];
constructor(private CFR: ComponentFactoryResolver) {
}
createComponent() {
let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
let currentComponent = componentRef.instance;
currentComponent.selfRef = currentComponent;
currentComponent.index = ++this.index;
// prividing parent Component reference to get access to parent class methods
currentComponent.compInteraction = this;
// add reference for newly created component
this.componentsReferences.push(componentRef);
}
remove(index: number) {
if (this.VCR.length < 1)
return;
let componentRef = this.componentsReferences.filter(x => x.instance.index == index)[0];
let component: ChildComponent = <ChildComponent>componentRef.instance;
let vcrIndex: number = this.VCR.indexOf(componentRef)
// removing component from container
this.VCR.remove(vcrIndex);
this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index);
}
第一个选项是迭代数组并通过带有 ngFor 的组件显示其内容的典型方式。第二个选项使用 ViewContainerRef 而不是 ngFor。可以在以下链接中看到一个示例。