Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reload component when change parts routing in angular

I use angular 6.

I have ListComponent which show list of products.

my routing

{
     path: ('list/:category/:subcategory'),
     component: ListComponent
}

a tag

<a class="link" [routerLink]="['/list/' + item.titleEn ]">
    {{ item.title }}
</a>

<a class="sub-link" [routerLink]="['/list/' + item.titleEn + '/' + itemSub.titleEn ]"
    {{ itemSub.title }}
</a>

now, when i click "/list/car/bmw" in HomeComponent (/home), that's worked and render ListComponent. but when i click "/list/car/bmw" in ListComponent (/list/car/benz), that's not working and not render ListComponent.

like image 882
Farid Karami Avatar asked Sep 20 '25 01:09

Farid Karami


1 Answers

  • When first "/list/car/bmw" is loaded then angular got one paramerized route "list/:category/:subcategory" which matching the "/list/car/bmw" url. so it will render your component ListComponent.

  • if by any action (button click or anchor click" if your url changed to "/list/car/benz" then it will not render ListComponent. As ListComponent is already loaded with parameterized route 'list/:category/:subcategory'. In this case route is not changing but the router params are changing.

And to detect the param change Please use ActivatedRoute to check any change to the parameters.

Step 1 - Do the constructor Injection of ActivatedRoute

constructor(private activatedRoute: ActivatedRoute) {
   // Code snippet
   this.subscribeRouteChange();
}

Step 2 - Subscribe to for route param change

subscribeRouteChange() {
    this.activatedRoute.params.subscribe((params = {}) => {
        // Will log any change to the route.
        // You can add your own logic here
        console.log(params.category);
        console.log(params.subcategory)
    });
}
like image 171
RANJIT PATRA Avatar answered Sep 21 '25 14:09

RANJIT PATRA