Solved – Angular router outlet appended the view instead of replacing it

Recently while working on an Angular project, we faced a very weird issue while working on one of the third-party plugins recently – the Angular router outlet appended the view instead of replacing it. We spent considerable amount of time searching for solution, before finally cracking it. We hope this article saves your time.

Problem

The router outlet did not load the component that we had asked it to load, instead it appended the view on top of the previous view.

Structure of our component looked something like this –

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

 

From the dashboard component (for which the route is ‘/dashboard’) we asked the router to replace the view with home component (for which the route is ‘/home).

This is how the navigation code looked like,

import { Router } from ‘@angular/router’;
constructor( private router: Router) {}
this.router.navigate([‘/home]);

But this did not work as expected. The layout after the router navigation looked something like this –

 

Angular router outlet appended the view instead of replacing

 

Instead of replacing, it placed the Home view above the Dashboard view!

 

Solution

We dug deeper to understand why this happened. Here’s what we found –

The plugin we used took the application out of Angular’s ecosystem (which is good as it optimizes performance when starting a work consisting of one or more asynchronous tasks that don’t require UI updates or error handling to be handled by Angular).

In the handler function of the plugin, the ‘this’ keyword that we had used did not hold proper value for the router object.

To force the chunk of code to execute back in the required and necessary “Angular ZONE” we just replaced the navigation code with the following lines,

import { Router } from ‘@angular/router’;
import { NgZone } from ‘@angular/core’; // do not forget the import 🙂
constructor( private router: Router , public zone: NgZone) {}
this.zone.run(() => { this.router.navigate([‘/home]); });

 

That’s it! 🙂

Happy Coding!

 

References

For more information on ngZone check out Angular docs at https://angular.io/api/core/NgZone