Search code examples
javascriptangulartypescriptangular-routing

Angular 2 router ngIf dynamic route


How to ngIf dynamic router ? For example I have top navigation component which has back button and I want that back button would only be visible on 'item/:id' route with:

*ngIf="router.url == '/item' or '/item/:id' - and it's not working.

How to *ngIf dynamic routes ?


Solution

  • You could build route guards. The canActivate guard turns on a flag and the canDeactivate turns off the flag. The navigation item would then be bound to that flag.

    Or you could add a routing even watcher that watches for specific events and turns on/off a flag that you can bind to.

    In this example, I'm using routing events to turn on/off a flag to manage a spinner:

      constructor(private authService: AuthService,
                  private router: Router,
                  private messageService: MessageService) {
        router.events.subscribe((routerEvent: Event) => {
          this.checkRouterEvent(routerEvent);
        });
      }
    
      checkRouterEvent(routerEvent: Event): void {
        if (routerEvent instanceof NavigationStart) {
          this.loading = true;
        }
    
        if (routerEvent instanceof NavigationEnd ||
            routerEvent instanceof NavigationCancel ||
            routerEvent instanceof NavigationError) {
          this.loading = false;
        }
      }
    

    You could do something similar watching for NavigationStart events for a particular set of routes. For example (not tried):

      constructor(private authService: AuthService,
                  private router: Router,
                  private messageService: MessageService) {
        router.events.subscribe((routerEvent: Event) => {
          this.checkRouterEvent(routerEvent, router.url);
        });
      }
    
      checkRouterEvent(routerEvent: Event, routerUrl: string): void {
        if (routerEvent instanceof NavigationStart && routerUrl == '/item') {
          this.myflag= true;
        }
    
        if (routerEvent instanceof NavigationEnd ||
            routerEvent instanceof NavigationCancel ||
            routerEvent instanceof NavigationError) {
          this.myflag= false;
        }
      }