Skip to main content

Router :: Subscribe to Route Changes

This example will change the function of a contextual button in a bootstrap/navbar

import { Component, OnInit } from "@angular/core";
import { Router, NavigationEnd } from "@angular/router";

import "rxjs/add/operator/filter";

@Component({
    selector: "my-app",
    templateUrl: `
        <nav class="navbar navbar-fixed-top navbar-light bg-faded">
            <a routerLink="/" class="navbar-brand">{{title}}</a>
            <div class="nav navbar-nav pull-xs-left">
                <a routerLink="/contacts" routerLinkActive="active" class="nav-item nav-link">Contacts</a>
                <a routerLink="/features" routerLinkActive="active" class="nav-item nav-link">Features</a>
                <a routerLink="/tools" routerLinkActive="active" class="nav-item nav-link">Tools</a>
            </div>
            <div class="nav navbar-nav pull-xs-right">
                <button routerLink="contextButtonLink" [disabled]="!contextButtonActive" type="button" class="btn btn-primary">{{contextButtonLabel}}</button>
            </div>
        </nav>
        <router-outlet></router-outlet>
`
})
export class AppComponent implements OnInit {
    title:string = "My App";

    contextButtonLabel:string = "New";
    contextButtonLink:string = "/";
    contextButtonActive:boolean = false;

    constructor(
        # inject the Router
        private router: Router,
    ) {
    }

    ngOnInit() {
        // subscribe to desired router changes, for example NavigationEnd events
        this.router.events.filter(
            e => e instanceof NavigationEnd
        ).subscribe(
            e => { this.contextButton(e); }
        );
    }

    contextButton(event) {
        if (event.urlAfterRedirects === "/contacts") {
            this.contextButtonLabel = "New";
            this.contextButtonLink = "/contacts/new";
            this.contextButtonActive = true;
        } else {
            // this.contextButtonLabel = "Disabled";
            // this.contextButtonLink = "/";
            this.contextButtonActive = false;
        }
    }
}