動態改變顯示的角度子組件 (Dynamically change displayed angular child component)


問題描述

動態改變顯示的角度子組件 (Dynamically change displayed angular child component)

我有一個父組件,我在其中設置了一組子組件(每個都擴展 BaseChild)。我使用 *ngFor 循環遍歷孩子並顯示他們的名字。我想點擊孩子的名字並將孩子的html插入父母。但是我不想在父 html 中硬編碼很多 *ngIf={{child1ShouldBeDisplayed}} ‑ 會有很多孩子,事情會變得非常醜陋。

我嘗試按照建議使用 ng‑content here,但似乎這是為了將父 html 注入孩子(來自 這裡)。我已經閱讀了 ng‑template, ng‑containerhere 但它似乎不符合我的需求。

這是一個 StackBlitz 設置基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?

這裡)。我已經閱讀了 ng‑template, ng‑containerhere 但它似乎不符合我的需求。

這是一個 StackBlitz 設置基本代碼。我不確定如何繼續。有沒有辦法在不使用大量 *ngIf 語句的情況下選擇在父項中顯示哪個子項?

這裡)。我已經閱讀了 ng‑template, ng‑containerhere 但它似乎不符合我的需求。

這是一個 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 FletchMarcell Kiss)

參考文件

  1. Dynamically change displayed angular child component (CC BY‑SA 2.5/3.0/4.0)

#Angular






相關問題

量角器,根據 API 請求使用 angular2 模擬後端 (Protractor, mocking backend with angular2 on api request)

XMLHttpRequest 響應:預檢請求未通過訪問控制檢查: (XMLHttpRequest response: preflight request does not pass the access control check:)

為 index.html 中的 src 標籤指定前綴 (Specify a prefix for the src tag in index.html)

模型更改後模板未更新 (Template not updating after model changed)

如何在 Ionic 4 firebase PWA 應用程序中將 promise 轉換為 observable (how do I convert a promise to observable in a Ionic 4 firebase PWA app)

如何以角度顯示漂亮的html (How to display pretty html in angular)

如何保持 Angular 組件的最新狀態? (How to keep the latest state of Angular components?)

在 mat-grid-tile Angular 上顯示 flex (display flex on mat-grid-tile Angular)

如何使用地圖構建離線 Electron 應用程序 (How to build an Offline Electron app with maps)

如何測試控制台值以滿足單元測試? (How to test console value to satisfy unit test?)

將表情符號插入 Angular 的輸入字段 (Insert emoticon into the input field in Angular)

如何在 Angular 中導入“數字”:“^1.2.6”? (How to import "numeric": "^1.2.6" in Angular?)







留言討論