What is the Angular 2 equivalent of $scope.watch?
I use $scope.watch to observe changes on objects from outside service that is used in my controller.
I know $scope does not apply anymore but how to setup a watch function?
You could use the ngOnChanges method to be notified if any bindings have changed:
@Component({
selector: 'my-cmp',
template: `<p>myProp = {{myProp}}</p>`
})
class MyComponent implements OnChanges {
@Input() myProp: any;
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
console.log('ngOnChanges - myProp = ' +
changes['myProp'].currentValue);
}
}
But it depends on your use case since you can also leverage (for example) form controls to be notified as well:
@Component({
selector: 'four',
directives: [MyDirective],
template: `
Hello, this is working! <br>
<textarea mydir [(ngModel)]="pp.status" [ngFormControl]="myCtrl">
</textarea>
`,
})
export class Four {
@Input() pp;
constructor() {
this.myCtrl = new Control();
this.myCtrl.valueChanges.subscribe(
(data) => {
console.log('Model change');
});
}
}
You could also leverage custom EventEmitter you can subscribe within services to notify outside your component.
You can use rx.js function Observable.of(something) for this.
import {Observable} from "rxjs/Rx";
class Example {
public test;
public watchTest;
constructor(){
this.setWatch()
this.seeWatch()
}
setWatch() {
this.watchTest = Observable.of(this.test);
}
seeWatch() {
this.watchTest.subscribe(data => {
data //this.test value
}
}
}