1

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?

Nearpoint
  • 7,040
  • 12
  • 43
  • 74

2 Answers2

4

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.

Thierry Templier
  • 191,422
  • 38
  • 386
  • 349
0

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
       }
    }

}
Gaurav Mukherjee
  • 6,005
  • 2
  • 23
  • 33
  • The subscription only fires for the initial value. `of` is intended for other use cases where a "single-shot" behavior makes sense. – snort Aug 20 '20 at 17:58