I am working on E-commerce project, in the shop page when user click on view more button on a product I send him to route for the product details page with the product id with him
<a [routerLink]="['/product-details', product.id]">View More</a>
when he enters the product page show him under the product details 4 products for the same brand so I have an API that I send the brand_id for this product and it returns randomly 4 products for this brand and when he click on product from the 4 products he must go to the page he is on currently but with different product id like this
<a [routerLink]="['/product-details', moreProduct.id]">View More</a>
the problem is that the URL is changed with the new id but the page content doesn't change to the new product till I reload the page, how can I fix this please.
When you need to use the Angular component with route params which may be changed within the component itself, you have to move the logic that depends on the route params to be called within the subscribe of ActivatedRoute.paramMap observable, to be called each time the params have been changed.
Try the following:
constructor(private activatedRoute: ActivatedRoute, ....) {}
ngOnInit(): void {
this.activatedRoute.paramMap
.subscribe((params) => {
const productId = params.get('PRODUCT_ID_PARAM_NAME');
// Get the related products here, or any other logic that depends on the params
});
}
Use the below code in your constructor. It will prevent angular from reusing the component and instead angular will recreate it.
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};