在Angular 2中,当我点击按钮时,它添加了类" newstyle"每个"按钮"在ngFor循环中...如何仅将ngClass条件绑定到元素本身?
<button [ngClass]="{'newstyle': isClicked }" (click)=" isClicked = !isClicked">Click button</button>
谢谢!
答案 0 :(得分:2)
试试这个:
<button *ngFor="let thing of things" [class.newstyle]="currentThing === thing" (click)="currentThing = thing">Click button</button>
您必须将currentThing添加为组件类的属性:
export YourComponent {
currentThing: any;
}
答案 1 :(得分:1)
类似于UseCase:遍历集合并为item-updated
中已编辑的items
应用特定的课程collection
。
此部分是可选的,仅适用于演示:[attr.title]="item.isDirty ? 'Item was updated' : null"
html组件
<div *ngFor="let item of collection">
<label>Name: {{item.name}}</label>
<button class="btn"
[ngClass]="{'item-updated' : item.isDirty}"
[attr.title]="item.isDirty ? 'Item was updated' : null">
Save
</button>
</div>
<强>说明:强>
只有当item.isDirty
条件匹配时,该按钮才会收到特定的类。
在您的情况下,从问题开始,所有按钮都绑定到相同的isClicked
属性。因此,无论编辑哪一个,您的属性都会更改,所有其他按钮都会收到最新的类。
修改强> 来自问题的代码段:
<button [ngClass]="{'newstyle': isClicked }" (click)=" isClicked = !isClicked">Click button</button>
<强>转化强>
HTML组件
<div *ngFor="let item of yourArray">
<label *ngIf="item.isClicked">Item was Clicked: {{item.id}}</label>
<button [ngClass]="{'newStyle' : !item.isClicked}" (click)="changeItemState(item)">Click button </button>
</div>
TS组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'your-component',
templateUrl: './your.component.html'
})
export class YourComponent implements OnInit {
public yourArray: any[];
public ngOnInit(): void {
this.yourArray = [
{
id: 1,
name: 'First',
isClicked: false;
},
{
id: 2,
name: 'Second',
isClicked: false;
},
{
id: 3,
name: 'Third',
isClicked: true;
},
];
}
public changeItemState(item: any): void {
item.isClicked = !item.isClicked;
}
}