jenesuispastom
jenesuispastom

Reputation: 159

Angular - Update ngFor index on filter

I have a list with an *ngFor in the template:

<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).

Any help with this? I'd need to update the productId in the template everytime I filter items in the array.

Upvotes: 0

Views: 722

Answers (2)

Max Ivanov
Max Ivanov

Reputation: 173

index as productId set index of product item in product array. It's similar to productId = products.indexOf(product). Try to use id property in product object

Upvotes: 0

Bhavik
Bhavik

Reputation: 124

It seems like you are trying to use index as a productId, I think you should use some property of product i.e. product.id or product.productId in your routerLink, e.g. Also, you don't need index as productId as well [ you can remove that as well]

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

Upvotes: 1

Related Questions