Search code examples
angularangular6angular-ng-if

Angular ngIf shows template on window, then removes from DOM


root component

<div class="container">
  <div class="row">
    <ng-container *ngIf="router.url !== '/login'">
      <app-navbar></app-navbar>
    </ng-container>
  </div>
  <ng4-loading-spinner></ng4-loading-spinner>
  <router-outlet></router-outlet>
  <div class="col-xs-12  col-sm-12 col-md-12">
    <ng-container *ngIf="router.url !== '/login'">
      <app-footer></app-footer>
    </ng-container>
  </div>
</div>

When I check if router.url (router injected on root component typescript on constructor) equals ./login then remove from DOM. But angular shows this template on 1-2 ms after loading page and then removes from DOM. But I don't want to visible <app-navbar></app-navbar> and <app-footer></app-footer> ..enter image description here


Solution

  • The problem is with the way you are getting current Route. In latest version of angular, Router does not return simple object. Instead it returns an observable with various redirection events. Router does not directly goes to the target URL, it goes through a specified path in order to reach target URL.

    You can use below code to get current route and store it in a variable and then compare it in your template.

    currentURL:any;
    
    constructor(private router: Router){
    
       this.router.events.filter((res) => res instanceof NavigationEnd).subscribe((res) => {
          this.currentURL = this.router.url;   
       });
    
    }
    

    also import NavigationEnd on top of your code

    import { Router, NavigationEnd } from '@angular/router';
    

    The above code will make sure you only get the last(target) URL of entire redirection cycle.