I have a custom button component which has a parameter list. List contains other angular components, eg <mat-checkbox>
and <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.
Have a flag variable in your component and when someone clicks your button you can toggle the components showing.
Example:
Your component.ts file:
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 -
@Input() components: Array<>;
Add an object for toggling which components exist in the array:
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:
<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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.