在 *ngFor 中执行索引减法

  • 本文关键字:索引 执行 ngFor angular
  • 更新时间 :
  • 英文 :

如何使用

索引进行计算?我想在条件为真时应用类危险,但我需要在 *ngFor 循环中计算 i-1。

<tr *ngFor="#org of data; #i = index">
    <td [ngClass]="{danger: org.price < data.stock[i-1].val }">
</tr>
我很

确定这不是由i-1不起作用引起的。
索引以 0 开头。因此,我想问题是data.stock[-1]只是无效,因为访问数组的索引-1是无效的。

您可以在自定义函数中进行所需的任何计算,例如:

@Component({
  selector: 'my-app',
  template: `<table>
               <tr *ngFor="let org of data; let i = index">
                 <td [ngClass]="{danger: org.price < org.stock[getIndex(i)].val }">
               ...
})
export class AppComponent implements OnInits {
    ...
    // this is your custom function to set index as you need
    getIndex(index){
        var result = index - 1;
        if (result < 0 || result > 0) result = 0;
        return result;
    }
}

在此处查看我的快速示例

注意:

  • 正如@Günter指出的:负指数无效
  • 您的data属性是对象数组还是只是一个对象?似乎它应该是一个对象数组,其中每个对象都有一个额外的数组属性,称为 stock .
  • *ngFor中的#组织已弃用,您应该改用 let。

最新更新