简体   繁体   English

Angular - 更新过滤器上的 ngFor 索引

[英]Angular - Update ngFor index on filter

I have a list with an *ngFor in the template:我在模板中有一个带有 *ngFor 的列表:

<li *ngFor="let product of products | filterProducts: selectedFilter; index as productId">
    <a [routerLink]="['/product', productId]">
      {{product.name}}
    </a>
</li>

So I use the filterProducts pipe to filter array items with selected options, but when the array changes it doesn't update the productId on the template, so the routerLink takes me to the wrong details page (it uses the productId in the original array).因此,我使用 filterProducts 管道来过滤具有选定选项的数组项,但是当数组更改时,它不会更新模板上的 productId,因此 routerLink 会将我带到错误的详细信息页面(它使用原始数组中的 productId) .

Any help with this?有什么帮助吗? I'd need to update the productId in the template everytime I filter items in the array.每次过滤数组中的项目时,我都需要更新模板中的 productId。

It seems like you are trying to use index as a productId, I think you should use some property of product ie product.id or product.productId in your routerLink, eg Also, you don't need index as productId as well [ you can remove that as well]似乎您正在尝试使用索引作为 productId,我认为您应该在您的 routerLink 中使用产品的某些属性,即 product.id 或 product.productId,例如另外,您也不需要索引作为 productId [您可以也删除它]

<li *ngFor="let product of products | filterProducts: selectedFilter; index as productId">
    <a [routerLink]="['/product', product.productId]">
      {{product.name}}
    </a>
</li>

index as productId set index of product item in product array. index as productId 设置产品数组中产品项的索引。 It's similar to productId = products.indexOf(product).它类似于 productId = products.indexOf(product)。 Try to use id property in product object尝试在产品对象中使用 id 属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM