简体   繁体   English

如何在列表 angular 9 中显示组件定义器

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

I have a custom button component which has a parameter list.我有一个自定义按钮组件,它有一个参数列表。 List contains other angular components, eg <mat-checkbox> and <button> .列表包含其他 angular 组件,例如<mat-checkbox><button>

Is there any way to display all the added components to the user when she presses the button?当她按下按钮时,有什么方法可以向用户显示所有添加的组件?

So far I have just a component but I have no idea how to render all component elements from that list.到目前为止,我只有一个组件,但我不知道如何呈现该列表中的所有组件元素。

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

You can do this by just using the *ngIf directive if I'm understanding your problem correctly.如果我正确理解您的问题,您只需使用 *ngIf 指令即可。

Have a flag variable in your component and when someone clicks your button you can toggle the components showing.在您的组件中有一个标志变量,当有人单击您的按钮时,您可以切换组件的显示。

Example:例子:

Your component.ts file:您的 component.ts 文件:

showContent = false;

And in your template:在您的模板中:

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

I suppose you have an input property in your show-button component like -我想您的show-button组件中有一个输入属性,例如-

@Input() components: Array<>;

Add an object for toggling which components exist in the array:添加一个 object 用于切换阵列中存在哪些组件:

injectedComponents = { 
    hasMatCheckBox: false,
    hasButton: false
}

Then toggle the properties based on which components are present in your array like:然后根据数组中存在的组件切换属性,例如:

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

Then in your html file, check for individual properties:然后在您的 html 文件中,检查各个属性:

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

This should work for 2 components, though a better solution would be provide the html yourself in the component where you are including the show-button component by using content projection eg这应该适用于 2 个组件,尽管更好的解决方案是在您使用内容投影包含show-button组件的组件中自己提供 html,例如

2nd METHOD:方法二:

Parent Component -父组件 -

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

Show Button Component -显示按钮组件 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM