[英]Dynamically load the components Angular 2
我正在嘗試動態加載組件數組。 我有一個包含所有需要在運行時加載的組件的數組。 以下代碼循環遍歷數組,並為組件創建工廠。 `
gAfterViewInit() {
this.loadcomponents();
}
loadcomponents() {
for (let i = 0; i < this.components.length; i++) {
//this.sidetext[i] = this.components[i].sidetext;
//this.section_ttile[i] = this.components[i].section_ttile;
for (let j = 0; j < this.components[i].components.length; j++) {
let termItem = this.components[i].components[j];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component);
let viewContainerRef = this.termHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<TermComponent>componentRef.instance).data = termItem.data;
}
}
`這是我的模板
<div class="div_for_ques" *ngFor="let component of components; let i=index">
<div class="sec_two">
<ng-template term-host></ng-template>
</div>
</div>
但是問題在於,動態加載的組件出現在先前加載的組件組件之上。 我希望每個組件都在一個單獨的div中。 關於如何實現這一目標的任何建議? 以下是當前的輸出。
預期的輸出是兩個這樣的輸入字段,但實際上只有第二個與第一個完全重疊。
您需要使用@ViewChildren
以便獲取容器的查詢列表。
您的模板可能是這樣的:
<div *ngFor="let v of views">
<div #target></div>
</div>
您的代碼將實例化如下組件:
@ViewChildren('target', {read: ViewContainerRef}) container: QueryList<ViewContainerRef>;
ngAfterViewInit(){
this.container.toArray().map((viewContainerRef, i) => {
let componentFactory = this.resolver.resolveComponentFactory(this.components[i]); // actually that should be this.components[i].components[j] something in your case
let componentRef = viewContainerRef.createComponent(componentFactory);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.