简体   繁体   中英

Angular2 bind event / DOM in ngFor loop

What is the best way to accomplish toggling div visibility inside ngFor like in example bellow? Each click should toggle div visibility from same iteration. The question is actually how to bind this event/DOM properly.

<div *ngFor="let hero of heroes; let i = index">
  <div [hidden]="?">Toggle my visibility</div>
  <div (click)="?">Click me</div>
</div>

I think the best solution will be to create another array with visibility properties. So, an array (each hero visible on load):

this.heroesVisibility = new Array(this.heroes.length).fill(true);

And the function in component class:

public toggleVisibility(id : number) : void {
    this.heroesVisibility = !this.heroesVisibility;
}

Then in template:

<div *ngFor="let hero of heroes; let i = index">
  <div [hidden]="!heroesVisibility[i]">Toggle my visibility</div>
  <div (click)="toggleVisibility(i)">Click me</div>
</div>

Make it an *ngIf="".. Make a boolean variable and change it on click.

Link to docs

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