首页 > 解决方案 > 如何在列表角度9中显示组件定义器

问题描述

我有一个自定义按钮组件,它有一个参数列表。列表包含其他角度分量,例如<mat-checkbox><button>

当她按下按钮时,有什么方法可以向用户显示所有添加的组件?

到目前为止,我只有一个组件,但我不知道如何呈现该列表中的所有组件元素。

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

标签: angularangular-materialangular9

解决方案


我想您的show-button组件中有一个输入属性,例如-

@Input() components: Array<>;

添加一个对象来切换数组中存在哪些组件:

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>

show-button这应该适用于 2 个组件,尽管更好的解决方案是通过使用内容投影在包含该组件的组件中自己提供 html,例如

方法二:

父组件 -

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

显示按钮组件 -

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

推荐阅读