Luki
Luki

Reputation: 447

How to dynamic change property value with ngFor loop using click method

I have a TypeScript file below:

<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>

and class Component:

export class PeopleComponent implements OnInit {
showHide() {

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

This below is model class.

export class People {
  public showAge: boolean;

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

And now how can I implement showHide() method in PeopleComponent when I click the button then age will be show and hide alternately? I'm working with Angular 4.

Upvotes: 1

Views: 1229

Answers (1)

Faly
Faly

Reputation: 13356

You already have a showAge property in the People class so...

<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){}
}

Upvotes: 1

Related Questions