简体   繁体   English

Angular 切换 boolean 变量来自位于 ngFor 内的同级组件

[英]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).案例如下,一个ngFor渲染一个组件集合(app-item)。 Each component has a boolean variable named "open" and a function named "toggle" that toggles (true or false) the variable.每个组件都有一个名为“open”的 boolean 变量和一个名为“toggle”的 function,用于切换(真或假)变量。

How can I click the button of a component (app-item) and change the state of the remaining iterated sibling items?如何单击组件(应用程序项)的按钮并更改剩余迭代同级项的 state?

app-page.component.html app-page.component.html

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

app-item.component.html应用-item.component.html

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

app-item.component.ts应用程序项.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我认为您有 3 个选项 1- 在 app-item-component 中使用 @output() 并向父组件发出事件,然后通过 @Input() 设置更改所有组件 state 2- 使用服务并在其中创建主题并订阅在子组件中 3- 将属性字段添加到您的项目 model 为 boolean 并在子组件或父组件中通过引用更改它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM