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