Search code examples
angularrxjsobservablengxs

Using ngxs observable select property in template


I've just started using Angular 6, so I apologise in advance for what is probably a very simple question. I've also just started looking into using ngxs for state management.

I've got a @Select Observable property from my state on my component.

@Select(HomeState.isLoading) isLoading$: Observable<boolean>;

My question is, how do I actually use isLoading in the component template? What's the general pattern here for using observable state properties in the template? Should I be subscribing to the observable and mapping the value to another property on the component, or is there a way to use the Observable in the template?

Of course, if it were just a straight up boolean, I could use it like *ngIf="isLoading" in the template.


Solution

  • the idea of using observables is allow to angular manage the subscription by using the 'async' pipe in the template, otherwise if you do it yourself at some point you will need to manage all the subscriptions by unsubscribing from the observable when the component is destroyed. in the example that you present isLoading variable can be used on the template to show or hide part of your component for example:

    <div *ngIf="isLoading$ | async">show loader</div>
    

    In my opinion a good pattern is always let the view handle the subscription!. If you need to transform the variable that is coming in the observable you always can pipe and transform the variable.