如何在点击* ngFor时选择特定的div?

时间:2017-09-08 12:48:11

标签: angular

我的模板中有这个:

 <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);
    }

2 个答案:

答案 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)

三个步骤:

  1. 你的Html

     <div [class]="divClass" *ngFor="let product of products;let i=index" (change)="sum(i)" (click)="selectItemForDelete(product)" [ngClass]="{'selected':products[i] == i}">
    

  2. 在您的组件中的 OnInit()下。

    ngOnInit(){ this.divClass="ui-g"}
    
  3. 点击div - 更改divclass的值

    selectItemForDelete(product){this.divClass="selected";}
    
  4. 多数民众赞成。