Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.x watching for variable change

I'm migrating from angular 1.x to 2.x but my brains still think in angular 1.x so sorry for silly questions.

What I need is to take some action when one of my scope variables component properties changes. I found a solution but I think there should be better solution

export class MyApp {     router: Router;     location: Location;     fixed: boolean = true;      private set isFixed(value:boolean) {         this.fixed = value;          //TODO: look here         console.log('isFixed changed', value);     }      private get isFixed():boolean {         return this.fixed;     }      constructor(router: Router, location: Location) {         this.router = router;         this.location = location;     } } 

Look at the line console.log('isFixed changed', value); It's what I need and it's working. But I made it by declaring getter and setter, but isn't there a better solution to watch variables? Like in angular 1.x was $scope.$watch?

I think my component code should look like

export class MyApp {     router: Router;     location: Location;     isFixed: boolean = true;      //TODO: $watch for isFixed change {         console.log('isFixed changed', value);     // }      constructor(router: Router, location: Location) {         this.router = router;         this.location = location;     } } 
like image 237
Arūnas Smaliukas Avatar asked Dec 23 '15 10:12

Arūnas Smaliukas


People also ask

How Angular 2 detect changes?

Change detection works by detecting common browser events like mouse clicks, HTTP requests, and other types of events, and deciding if the view of each component needs to be updated or not.

What is the angular equivalent to an Angularjs watch?

You can use getter function or get accessor to act as watch on angular 2.


1 Answers

You might want to implement the OnChanges interface and implement the ngOnChanges() method. This method is called whenever one of the components input or output binding value changes. See also https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

Dart code example

  @Input() bool fixed;    @override   void ngOnChanges(Map<String, SimpleChange> changes) {     print(changes);   } 
like image 75
Günter Zöchbauer Avatar answered Sep 19 '22 22:09

Günter Zöchbauer