0

I have a list of child components inside a ngFor:

<ng-container *ngFor="let field of fields">
 <button (click)="show = !show">Show</button>
 <ng-container *ngIf="show">
  <app-field [fieldInfo]="field"></app-field>
 </ng-container>
</ng-container>

I want to only show this specific app-field component if show is true, but this is obviously not the way, because it sets show to true for all of the rendered components.

My problem is really that I cant show all of the app-fields because they turn my app into a slow mess when they are displayed (there will be hundreds of them), so I only want to display them when they are needed.

How can I toggle the rendering of each specific component on/off uppon click? Or is there som other solution I could look into?

2 Answers2

2

show variable is global and updating value for show will reflect for all the app-field components, Thus You need to determine and specify a show/hide variable for each component individually.

To do that you should add a show member inside the field Object as follow:

<ng-container *ngFor="let field of fields">
 <button (click)="field.show = !field.show">Show</button>
 <ng-container *ngIf="field.show">
  <app-field [fieldInfo]="field"></app-field>
 </ng-container>
</ng-container>

Also found similar solution, check this answer

yazan
  • 518
  • 3
  • 16
0

I needed to only have the component be attached to the DOM when set to be visible. Solved it with the answer in: Thierry Templier answer here

Inside parent component:

public showField: any = {};

Then in parent component template:

<ng-container *ngFor="let field of fields">
 <button (click)="showField[childField.id] = !showField[childField.id]">Show</button>
 <ng-container *ngIf="showField[childField.id]">
  <app-field [fieldInfo]="field"></app-field>
 </ng-container>
</ng-container>

This destroys the component when *ngIf is false, which is what I needed in this situation.

Thanks to @yazan for leading me to the answer.