简体   繁体   中英

Angular toggle boolean variable from sibling components located inside an ngFor

The case is as follows, an ngFor renders a collection of components (app-item). Each component has a boolean variable named "open" and a function named "toggle" that toggles (true or false) the variable.

How can I click the button of a component (app-item) and change the state of the remaining iterated sibling items?

app-page.component.html

<div *ngFor="let item of items">
  <app-item [data]="item"></app-item>
</div>

app-item.component.html

<button (click)="toggle($event)">Toggle "open" variable.</button>
<div *ngIf="open">Content is now visible</div>

app-item.component.ts

export class ItemComponent {    
  open: boolean = false;

  toggle(event: any) {
     this.open = !this.open;
  }
}

I think you have 3 options 1- use @output() in app-item-component and emit an event to parent component then change all component state by @Input() set 2- use a service and create a subject inside it and subscribe in child components 3- add a property field to your item model as boolean and change it by refrence in child or parent components

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