我的模板中有这个:
<div class="ui-g" *ngFor="let product of products;let i=index" (change)="sum(i)" (click)="selectItemForDelete(product)" [ngClass]="{'selected':products[i] == i}">
</div>
我想要的是在点击的div上添加类selected
。任何建议我怎么能这样做?
这是我点击的方法:
selectItemForDelete(item): void {
if (this.selected.indexOf(item) === -1) this.selected.push(item);
else this.selected.splice(this.selected.indexOf(item), 1);
}
答案 0 :(得分:2)
[ngClass]="{'selected':products[i] == i}"
应该是
[ngClass]="{'selected':selected.includes(product)}"
我认为更有效的方法是创建一个大小为products
的第二个数组。
constructor() { // ngOnInit(), ...
this.products = someValue; // whereever `products` is initialized
this.selected = this.products.map((p) => false);
}
selectItemForDelete(idx:number): void {
selected[idx] = !selected[idx];
}
与
<div class="ui-g"
*ngFor="let product of products;let i=index"
(change)="sum(i)"
(click)="selectItemForDelete(idx)"
[ngClass]="{'selected':selected[i]}">
</div>
答案 1 :(得分:0)
三个步骤:
你的Html
<div [class]="divClass" *ngFor="let product of products;let i=index" (change)="sum(i)" (click)="selectItemForDelete(product)" [ngClass]="{'selected':products[i] == i}">
在您的组件中的 OnInit()下。
ngOnInit(){ this.divClass="ui-g"}
点击div - 更改divclass的值
selectItemForDelete(product){this.divClass="selected";}
多数民众赞成。