I've a simple question about change detection.
I have a component and a (global) service with a boolean inside. How can I make the component listen to that boolean and execute a function if that boolean changes?
Thanks!
I've a simple question about change detection.
I have a component and a (global) service with a boolean inside. How can I make the component listen to that boolean and execute a function if that boolean changes?
Thanks!
The Sam's answer is completely right. I would just want to add that you could also leverage a TypeScript setter to automatically trigger the event for changes:
Depending on how that boolean changes you could expose it as an
Observable<boolean>
on your service, and then subscribe to that stream in your component. Your service would look something like:Then in your component you would have something like this:
Now depending on what you need to do with that bool value you may need to do some other things to get your component to update, but this is the gist of using an observable.
Another option is you use the async pipe within your template instead of explicitly subscribing to the stream in the constructor. Again though, that depends on what exactly you need to do with the bool values.