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; } }
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.
You can use getter function or get accessor to act as watch on angular 2.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With