如何使用click方法使用ngFor循环动态更改属性值

时间:2017-09-15 09:04:42

标签: angular typescript

我有一个TypeScript文件:

<md-card style="display: inline-block;" *ngFor="let people of peoples">
    <p>
      {{people.name}}
    </p>
    <p *ngIf="people.showAge">
      {{people.age}}
    </p>
    <button md-button (click)="showHide()">Click me!</button>
</md-card>

和类组件:

export class PeopleComponent implements OnInit {
showHide() {

  }
peoples: People[] = [
    new People('John', 26),
    new People('Mary', 30),
    new People('Max', 15)]
}

以下是模型类。

export class People {
  public showAge: boolean;

  constructor(public name: string, 
              public age: number,
              ){}
}

现在,当我单击按钮时,如何在PeopleComponent中实现showHide()方法,然后将交替显示和隐藏年龄?我正在使用Angular 4。

1 个答案:

答案 0 :(得分:1)

您已在People类中拥有showAge属性,因此......

<md-card style="display: inline-block;" *ngFor="let people of peoples">
    <p>
      {{people.name}}
    </p>
    <p *ngIf="people.showAge">
      {{people.age}}
    </p>
    <button md-button (click)="people.showAge = !people.showAge">Click me!        
</button>
</md-card>

export class People {
      public showAge: boolean = false;
      constructor(public name: string, public age: number){}
}