简体   繁体   中英

How to update the style of all the items which are iterated using *ngFor in Angular

How do I apply style to all the items in the list which are iterated using *ngFor when clicked on a button which is outside the list.

<button (click)="markAllAsChecked();">Mark All as Checked</button>
<ion-list>
  <div *ngFor="let item of items">
    <ion-item (click)="this.item.checked = !this.item.checked;">
      <div class="item" [ngStyle]="{background: item.checked ? 'green': 'red'}">
        {{item.name}}
      </div>
    </ion-item>
  </div>
</ion-list>

I wanted all the items background color to be turned to green when clicked on Mark All as Checked button.

I created a working example using Stackblitz. Could anyone please help?

Your need to iterate on each item and make checked to true.

markAllAsChecked(){
  this.items.forEach(item => item.checked = true);
}

and if you want to toggle background colour on same button then,

markAllAsChecked(){
      this.items.forEach(item => item.checked = !item.checked);
}

here is the working link.

use [ngClass] instead of [ngStyle]

 <div class="item redBackgroundClass" [ngStyle]="{'greenBackgroundClass': item.checked}">

here keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed

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.

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