[英]Angular: How can I change the value of a property of a component inside an ngFor
Inside an ngFor I have a tabs component.在 ngFor 中,我有一个 tabs 组件。 To add a CSS class I use the property
show
which is a boolean false
.要添加一个 CSS 类,我使用属性
show
,它是一个布尔值false
。 If I click the component the show
property toggles to true
.如果我单击该组件,
show
属性将切换为true
。 If I click a second component I need to set false
previous clicked component.如果我单击第二个组件,我需要将先前单击的组件设置为
false
。
How can I access and set false
the show
property of the sibling components?如何访问和设置同级组件的
show
属性为false
?
export class TabComponent implements OnInit {
show: Boolean = false;
toggle(event: any) {
this.show = !this.show;
}
}
<ng-container *ngFor="let tab of tabs">
<app-tab [ngClass]="show ? 'open':'closed'" (click)="toggle($event)"></app-tab>
</ng-container>
You have to add Input()
to control state in each tab.您必须添加
Input()
来控制每个选项卡中的状态。
export class TabComponent implements OnInit {
@Input()
show: boolean = false;
toggle(event: any) {
this.show = !this.show;
}
}
<ng-container *ngFor="let tab of tabs">
<app-tab
[show]="tab.show" // or any value you need here
[ngClass]="tab.show ? 'open':'closed'"
(click)="toggle($event)">.
</app-tab>
</ng-container>
I would use the index value delivered by the *ngFor
, store the tab shown index and use it in the ngClass
condition like this :我将使用
*ngFor
提供的索引值,存储选项卡显示的索引并在ngClass
条件中使用它,如下所示:
export class TabComponent implements OnInit {
tabShownIndex = null;
toggle(index: number) {
this.tabShownIndex = index;
}
}
<ng-container *ngFor="let tab of tabs; let index = index;">
<app-tab [ngClass]="index === tabShownIndex ? 'open':'closed'" (click)="toggle(index)"></app-tab>
</ng-container>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.