revathi
revathi

Reputation: 205

How to watch route change and change value of boolean variable every time route changes in Angular 2?

I have a header component where I am making few boolean variables true to make the buttons visible in html. So basically in angular 1.x we were using watch on location.path. But in angular 2, I understand we don't have watch. When i explored more about how to achieve this, I came across topics like change detection, ngOnChange, Observable, router.subscribe etc.. I am new to Angular 2 and using Angular 2.0.0-beta.15.I cannot understand which topic i should read to find solution. Can somebody help me which topic is relevant to my situation?

Upvotes: 1

Views: 3763

Answers (2)

Tuan Bach Van
Tuan Bach Van

Reputation: 164

If you're using @angular/router from version 3.0.0-beta.2 They have changed method to subscribe

import {Router} from "@angular/router";

@Component({
.....
})
export class YourCmp {


    constructor(private router: Router) {
        this.router.events.subscribe(route => {
            console.log(route.url);
        });
    }
}

Upvotes: 3

Ankit Singh
Ankit Singh

Reputation: 24945

import {Router} from 'angular2/router';

@Component({
.....
})
export class YourCmp {

   someVar: boolean = false;

   constructor(private router: Router){

         this.router.subscribe(() => {
           // this code will run on every route change
          // do what you want, here

             this.someVar = !this.someVar;
        });

   }    
}

Upvotes: 2

Related Questions