Search code examples
angularangular-routing

Different routes, same component - why component not reload on route change?


I have 2 components, a parent and a child. The same parent component should load on 2 different routes, let's say route1 and route2. The parent component checks which route was used and sets a boolean regarding (isRoute1). The child component gets this boolean as an Input and render HTML regarding. See the skeleton code below.

Let's say first I open route1 in the browser. I could see 'Parent init' and 'Child init' texts in the console and the child component renders 'ROUTE1'. Everything is working as expected. Next, I navigate to route2 in the browser (directly from route1) and I have got some unexpected results. In the console, nothing shows up (so the OnInits didn't trigger) however the child rendered 'ROUTE2'. Why Angular didn't trigger the OnInit() function? How could I achieve that? I thought on route change the parent component will reload so the child.

// Parent component's TS
isRoute1: boolean;
ngOnInit(): void {
console.log('Parent init')
this.router$.pipe(debounceTime(1), untilDestroyed(this)).subscribe(route => {
  this.isRoute1 = route.params.id === 'route1';
});}

// Parent component's HTML
<child-component [isRoute1]="isRoute1"></child-component>


// Child component's TS
@Input()
isRoute1: boolean;

ngOnInit(): void {
  console.log('Child init')
}

// Child component's HTML
<div *ngIf="isRoute1; else route2"> ROUTE1 </div>
<div #route2> ROUTE2 </div>

Solution

  • In your ngOnInit() you can subscribe to the paramMap Observable to detect changes of the parameters in the same route:

    export class HelloComponent implements OnInit {
      id: any;
    
      constructor(private route: ActivatedRoute) {}
    
      ngOnInit() {
        this.route.paramMap.subscribe(params => {
          this.id = params.get('id');
          // Do more processing here if needed
        });
      }
    }
    

    Check this demo: https://stackblitz.com/edit/angular-vgz4yc

    As you can see, the ngOnitInit is executed only once but you can watch on the changes of the route parameters.

    To answer your question: The component won't reload if the route doesn't change (parameter change is not enough). But that doesn't matter because you can subscribe to paramMap and, when it emits a new value, do what ever processing you want.