Angular 中 *ngFor 的递减索引

Decrement Index of *ngFor in Angular

使用 Angular 4.0.2,我有一个 *ngFor 创建输入元素并通过添加按钮更新对象数组,但我想弄清楚如何在项目已从该数组中删除。

目前,我的 ngFor 看起来像:

*ngFor = let name of names; let i = index

然后,我的删除按钮有一个(点击)事件:

(click)="removeRow(i, names)"

方法如下:

    removeRow(index:number, names:Names[]){
        names.splice(index,1);
        index--;
    }

但是,当我在删除对象后去更新数组中的另一个输入元素时,索引不正确。看来 *ngFor 中的 "let i = index" 不会递减,我显然不能只使用:

(click)="removeRow(i, names); i--"

没有看到更多你的代码......这只是一个猜测。但我假设你也有组件的名称 属性 class?

尝试将名称数组传递到方法中,而只是从绑定名称中删除元素属性。 Angular`s 数据绑定应该会处理剩下的事情。

模板:

<tr *ngFor='let product of products; let i = index'>
    <td>
        <img    [src]='product.imageUrl'
                [title]='product.productName | uppercase'
                (click)="removeRow(i)">
    </td>
</tr>

我有一张图片,所以使用了点击它...但它在按钮上的效果相同。

组件class:

removeRow(index: number): void {
    this.products.splice(index,1);
}

此外,我在模板中使用 {{i}} 显示了 "i" 的值,并且在删除一行后 "i" 值 正确针对新的一组指数进行了调整。

i 不是按值传递给您的删除行函数吗?如果是这样,您必须在它存在的相同范围内递减它(在 ngFor 循环内)。

示例:https://snook.ca/archives/javascript/javascript_pass

不需要手动修改*ngFor设置的索引。 Angular 通过双向数据绑定来处理它。当您修改组件中的 "names" 数组时,视图将自行更新以反映更改,这包括 *ngFor 上的索引。

*ngFor:

*ngFor="let name of names; let i = index"

点击事件:

(click)="removeRow(i)"

组件方法:

removeRow(index:number){
    this.names.splice(index,1);
}

请注意,您不需要将数组从视图传递到组件,因为组件中已有它。

编辑:Plunker