問題描述
動態改變顯示的角度子組件 (Dynamically change displayed angular child component)
我有一個父組件,我在其中設置了一組子組件(每個都擴展 BaseChild)。我使用 *ngFor 循環遍歷孩子並顯示他們的名字。我想點擊孩子的名字並將孩子的html插入父母。但是我不想在父 html 中硬編碼很多 *ngIf={{child1ShouldBeDisplayed}}
‑ 會有很多孩子,事情會變得非常醜陋。
我嘗試按照建議使用 ng‑content
here,但似乎這是為了將父 html 注入孩子(來自 這裡)。我已經閱讀了 ng‑template, ng‑container
等 here 但它似乎不符合我的需求。
這是一個 StackBlitz 設置基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?
這裡)。我已經閱讀了ng‑template, ng‑container
等 here 但它似乎不符合我的需求。 這是一個 StackBlitz 設置基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?
這裡)。我已經閱讀了ng‑template, ng‑container
等 here 但它似乎不符合我的需求。 這是一個 StackBlitz 設置基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?
ng‑template、ng‑container 等 here 但它似乎不符合我的需求。這是一個 StackBlitz 設置上基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?
ng‑template、ng‑container 等 here 但它似乎不符合我的需求。這是一個 StackBlitz 設置上基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?
參考解法
方法 1:
There is a great tutorial for this on the official Angular site, with a stackblitz example.
Summary
You need to create a directive. You'll apply your components dynamically through this directive:
@Directive({
selector: '[dynamic‑stuff]',
})
export class DynamicStuffDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
You need a reference to this element (<ng‑emplate dynamic‑stuff></ng‑template>
):
@ViewChild(DynamicStuffDirective, {static: true}) dynamicStuff: DynamicStuffDirective;
You have to create a component factory for your component:
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(selectedComponent);
You have to apply it through the viewContainerRef of the directive:
this.dynamicStuff.viewContainerRef.clear();
this.dynamicStuff.viewContainerRef.createComponent(componentFactory);
Good luck, I hope I could help.
(by Fletch、Marcell Kiss)