Skip to content Skip to sidebar Skip to footer

Angular Toggle Class Only On Single Div

data test = [ { 'test1': { 'qq': ['qq', 'ww', 'aa', 'bb'], }, }, { 'test1': { 'qq': ['11', '22', '33', '44'], },

Solution 1:

The *ngFor do not create multiple instances, you have actually only one instance. So if you change the status all your divs will change.

The solution is to create a childComponent, the *ngFor will iterate and create as many component instance as items.

With that, every component (item) will have it own status.

I hope this will help !

Solution 2:

Depending on the structure of your array, you might need to pass the targeted item to the click handler. Which in your case list.test1.qq[1] or list.test1.qq[0].

Then you might need to separately tell your component which item is clicked, because the targeted item in your case is a string.

In my working solution, I've just defined a string called clicked which will memorize and toggle the targeted item and passed the targeted item to the click handler.

My Working Soulution on stackblitz

Solution 3:

<div class= "container">
<li *ngFor="let list of test"></li><divclass="a" (click)="clickEvent(list)" [ngClass]="list.status ? 'blue' : ''">
    {{list.test1.qq[0]}}
    </div><divclass="a" (click)="clickEvent(list)" [ngClass]="list.status ? 'blue' : ''">
    {{list.test1.qq[1]}}
    </div>
</div>

Post a Comment for "Angular Toggle Class Only On Single Div"