[英]Loading Dynamic Components using ngTemplate in ngFor
我試圖像這樣建立一個動態擴展面板:
<mat-accordion>
<mat-expansion-panel *ngFor="let category of categories">
<mat-expansion-panel-header>
<mat-panel-title>
{{category.name}}
</mat-panel-title>
</mat-expansion-panel-header>
<ng-template #category>
<a>Test</a>
</ng-template>
<mat-action-row>
<button mat-button color="primary" (click)="nextStep()">Next</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
在我的組件中,我試圖像這樣訪問每個模板:
@ViewChildren('category') components: QueryList<CategoryDirective>;
和
ngAfterViewInit() {
const viewContainerRef = this.adHost;
if (!_.isUndefined(this.categories) && !_.isUndefined(this.components)) {
this.components.changes.subscribe(() => {
this.components.toArray().forEach(el => {
console.log('ngAfterViewInit', el);
});
});
}
}
對於每個類別,我都有一個要在ngTemplate中加載的component屬性。
我怎么做?
由於多個“類別”指令,@ ViewChild無效。 您可以通過為每個項目創建一個單獨的組件來解決此問題。
<mat-accordion>
<ng-template ngFor let-category [ngForOf]="categories" let-i="index">
<expansion-panel [title]="category.name" [component]="category.component" [isSelected]="category.isSelected" [index]="i"></expansion-panel>
</ng-template>
</mat-accordion>
HTML:
<mat-expansion-panel [disabled]="!isSelected">
<mat-expansion-panel-header>
<mat-panel-title>
{{title}}
</mat-panel-title>
</mat-expansion-panel-header>
<ng-template category></ng-template>
<mat-action-row>
<button mat-button color="primary" (click)="nextStep()">Next</button>
</mat-action-row>
</mat-expansion-panel>
並在擴展面板組件中添加以下內容。
TS:
@ViewChild(CategoryDirective) categoryDirective: CategoryDirective;
和
@Input() component: any;
之后,您可以動態添加組件:
ngAfterViewInit(): void {
if (!_.isUndefined(this.component)) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
const viewContainerRef = this.categoryDirective.viewContainerRef;
console.log(viewContainerRef);
if (!_.isUndefined(viewContainerRef)) {
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
// (<CategoryComponent>componentRef.instance).data = adItem.data;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.