1

I'm trying to toggle an element to show/hide when I click on the title. So far I have this approach

<div class="parent" (click)="status=!status" [ngClass]="status ? 'hide' : 'display'">
   <div class="child">
     <p>Info to show or hide</p>
   </div>
</div>

On CSS file I have this

.hide .child {
  display: none;
}

This works fine for what I need when I have one element. But I want to display several of this items with an *ngFor. When I do that, then variable status is shared and clicking on any of the other elements will toggle all of them. Since the creation of elements is dynamic, is there any way to limit the scope of status variable to just that element? Or is there a better approach to this?

Rene Trujillo
  • 379
  • 3
  • 16

2 Answers2

1

YOu need a status variable in each object

<div *ngFor="let item of items" class="parent" (click)="item.status=!item.status" [ngClass]="item.status ? 'hide' : 'display'">
   <div class="child">
     <p>Info to show or hide</p>
   </div>
</div>
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

In yours component.ts file, add property status in each array element and assign true to element.status.

Then loop over the elements of array using ngFor and use element.status to toggle specefic element as below in your component.html file:

<div *ngFor="let element of myArray" class="parent" (click)="element.status=!element.status" [ngClass]="element.status ? 'hide' : 'display'">
    <div class="child">
        <p>Info to show or hide</p>
    </div>
</div>
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21