如何更新在Angular中使用* ngFor迭代的所有项目的样式

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 created a working example using Stackblitz. Could anyone please help?

评论
  • qqgsd
    qqgsd 回复

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

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

    如果要在同一按钮上切换背景色,

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

    here is the working link.

  • Stanf
    Stanf 回复

    use [ngClass] instead of [ngStyle]

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

    这里的键是CSS类,当值中给出的表达式计算为真实值时会添加这些CSS类,否则它们将被删除