I have a component where I get a route parameter:
export class CatalogComponent implements OnInit {
category: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.subscribe(parameters => {
this.category = parameters.has('category') ? +parameters.get('category') : undefined;
})
}
}
Then on the template I have:
<product-list [category]="category"></product-list>
And ProductList component is:
export class ProductListComponent implements OnInit {
@Input() category: number;
products$: Observable<ProductListModel[]>;
constructor(private productService: ProductService) { }
ngOnInit() {
this.products$ = this.getProducts();
}
private getProducts(): Observable<ProductListModel[]> {
return this.productService.get(this.category);
}
}
The problem is when route parameter category
changes the Products rendered by ProductList component are not updated.
How can I solve this?
you need to implement ngOnChanges
in ProductListComponent
like below
ngOnChanges(changes: Record<keyof ProductListComponent, SimpleChange>) {
if (changes.category && changes.category.currentValue) {
// reload your data here
}
}