【问题标题】:Toggle all Local Variables in *ngFor From Outside Loop从外部循环切换 *ngFor 中的所有局部变量
【发布时间】:2018-03-30 17:50:24
【问题描述】:

假设我有一个 *ngFor 循环,我在本地范围内定义了一个变量,例如:

<div *ngFor="let item of items">
  <p>{{item.name}}</p>
  <div *ngIf="item.colorVisible">{{item.color}}</div>
  <button (click)="item.colorVisible = !item.colorVisible">Toggle Color</button>
</div>

我正在循环一个对象数组,所以打字稿中的虚拟数组是:

export class AppComponent  {
  items = [
    {
      name: 'John',
      color: 'Green'
    },
    {
      name: 'Jim',
      color: 'Blue'
    },
    {
      name: 'Jane',
      color: 'Orange'
    }
  ]
}

如何在循环之外有一个按钮来切换所有变量,然后更新范围内的变量?

这是StackBlitz

【问题讨论】:

  • “更新范围内的变量”是什么意思?

标签: arrays angular typescript ngfor angular-ng-if


【解决方案1】:

只需向您的组件添加一个布尔属性并创建一个方法来循环您的项目。

组件

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public allVisible = false;
  items = [
    {
      name: 'John',
      color: 'Green',
      colorVisible: false
    },
    {
      name: 'Jim',
      color: 'Blue',
      colorVisible: false
    },
    {
      name: 'Jane',
      color: 'Orange',
      colorVisible: false
    }
  ]

  toggleAll() {
    this.allVisible = !this.allVisible;
    this.items.forEach((item) => {
        item.colorVisible = this.allVisible;
    });
  }
}

模板

<button (click)="toggleAll()">Toggle All Colors</button>

forked your StackBlitz.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多