簡體   English   中英

如何在列表 angular 9 中顯示組件定義器

[英]How to show components definer in list angular 9

我有一個自定義按鈕組件,它有一個參數列表。 列表包含其他 angular 組件,例如<mat-checkbox><button>

當她按下按鈕時,有什么方法可以向用戶顯示所有添加的組件?

到目前為止,我只有一個組件,但我不知道如何呈現該列表中的所有組件元素。

<show-button title="Show components" components=["<mat-checkbox", "<button>"]></show-button></div>

如果我正確理解您的問題,您只需使用 *ngIf 指令即可。

在您的組件中有一個標志變量,當有人單擊您的按鈕時,您可以切換組件的顯示。

例子:

您的 component.ts 文件:

showContent = false;

在您的模板中:

<show-button (click)="showContent = !showContent">Show Components</show-button>
<ng-container *ngIf="showContent">
  <mat-checkbox></mat-checkbox>
  ....
</ng-container>

我想您的show-button組件中有一個輸入屬性,例如-

@Input() components: Array<>;

添加一個 object 用於切換陣列中存在哪些組件:

injectedComponents = { 
    hasMatCheckBox: false,
    hasButton: false
}

然后根據數組中存在的組件切換屬性,例如:

ngOnInit() {
    this.injectedComponents.hasMatCheckBox = this.components.includes("mat-checkbox");
    this.injectedComponents.hasButton = this.components.includes("button");
}

然后在您的 html 文件中,檢查各個屬性:

<button *ngIf="injectedComponents.hasButton"></button>
<mat-checkbox *ngIf="injectedComponents.hasMatCheckBox"></mat-checkbox>

這應該適用於 2 個組件,盡管更好的解決方案是在您使用內容投影包含show-button組件的組件中自己提供 html,例如

方法二:

父組件 -

<show-button title="Show components">
    <button></button>
    <mat-checkbox></mat-checkbox>
</show-button>

顯示按鈕組件 -

<div>
    <ng-content></ng-content>
<div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM