This does not answer the question directly, but I have on different occasions landed on this Stack Overflow question in order to solve something I would use $watch for in angularJs. I ended up using another approach than described in the current answers, and want to share it in case someone finds it useful.
The technique I use to achieve something similar $watch
is to use a BehaviorSubject
(more on the topic here) in an Angular service, and let my components subscribe to it in order to get (watch) the changes. This is similar to a $watch
in angularJs, but require some more setup and understanding.
In my component:
export class HelloComponent {
name: string;
// inject our service, which holds the object we want to watch.
constructor(private helloService: HelloService){
// Here I am "watching" for changes by subscribing
this.helloService.getGreeting().subscribe( greeting => {
this.name = greeting.value;
});
}
}
In my service
export class HelloService {
private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
constructor(){}
// similar to using $watch, in order to get updates of our object
getGreeting(): Observable<{value:string}> {
return this.helloSubject;
}
// Each time this method is called, each subscriber will receive the updated greeting.
setGreeting(greeting: string) {
this.helloSubject.next({value: greeting});
}
}
Here is a demo on Stackblitz