是否可以在* ngFor内部增加组件属性值?

时间:2018-07-20 13:14:32

标签: javascript angular

我想为ngFor的每次迭代增加1的类属性,让我知道是否有办法。谢谢。

组件类:

class AA
   {      
  property:number = 0;
   }

模板:

 <div *ngFor = "let sample of samples">
    //increment property here
 </div>

2 个答案:

答案 0 :(得分:1)

您可以使用index

 <div *ngFor = "let sample of samples;let i = index">
    <span [class]="'opacity-'+(i+1)">value {{i+1}}</span>
    <button (click)="property = (i+1)">Set Selected Item</button>
 </div>
Selected Item : {{property}}

答案 1 :(得分:1)

只需在您的类中创建一个函数并将其调用到ngfor bloc中

class AA
   {      
  property:number = 0;
  
  function increment_property(): void{
    this.property++;
  }
   }

<div *ngFor = "let sample of samples">
    {{ increment_property() }}
 </div>