Home > Software engineering >  Angular 14: Routing to child route not working properly
Angular 14: Routing to child route not working properly

Time:09-26

In my Angular 14 application I have tree on the left side which contains buildings and persons inside these buildings.

      Building 1
       - Person 1
       - Person 2
       - Person 3
      Building 2
       - Person 4
       - Person 5

When I click an entry in the tree I want to display some details on the right side of the browser window. Therefore, I created a HTML template which contains the tree and a <router-outlet> for rendering the child components.

      <div >
        <div >
          ...
        </div>
      </div>

      <div >
        <router-outlet></router-outlet>
      </div>
    </div>

The routes are defined in this way:

    const routes: Routes = [
      { path: '', component: MainComponent, canActivate: [AuthGuard], 
        children: [
          { path: 'building/:uuid', component: BuildingComponent},
          { path: 'person/:uuid', component: PersonComponent},
        ]
      },
    ];

When I click an entry I call a method in the Maincomponent routing to the corressponding child compoment:

    this.router.navigate(['building', buildingUuid], {relativeTo: this.route})

    or

    this.router.navigate(['person', personUuid], {relativeTo: this.route})

This works fine if I switch between building and person items. In this case the child component is shown in the right part of the browser window.

But when I click two nodes of the same type after each other (e.g. Person 1 and then Person 2) I see that the URL in the browser changes, but the child component is not updated.

Any ideas, what I'm doing wrong?

CodePudding user response:

It's because you are already navigated to that component, so the component is already created and will not be created again.

What you should do is to subscribe to the params in the ngOnInit, so your logic will be executed on each param change:

import { ActivatedRoute} from '@angular/router';

...

constructor(private route: ActivatedRoute) {}

...

ngOnInit() {
  this.route.params.subscribe({
    next: (params) => {
      const uuid = params.uuid;
      // Your logic
    },
    error: (error) => {
      console.log('ERROR: ', error);
    },
  });
}

Note: Don't forget to unsubscribe from Observable in ngOnDestroy.

  • Related