DEV Community

loading...

How simplify nested async subscriptions in Angular template

danywalls profile image Dany Paredes ・1 min read

One way to suscribe to observable in Angular is async pipe into the html template. It is easy but when you have several subscription use ng-container with *ngIf is a common solution, like :

<ng-container *ngIf="userAuth$ | async as user">
    <span column-1 class="licence-name">
        {{user.role}}
    </span>
    <ng-container *ngIf="domains$ | async as domains">
      <ul *ngFor="let domain in domains">
        <li>{{domain}}</li>
    </ng-container>
<ng-container *ngIf="ads$ | async as ads">
       <div *ngFor="let ad in ads">
           {{ad.name}}
       <div>
</ng-container>
<ng-container 
</ng-container>
Enter fullscreen mode Exit fullscreen mode

use Object :)

The ng-contanier generate too noise into the DOM but we can simplify using object into a single ngIf and grouping each suscription into it object like:

<ng-container *ngIf="{
    user: userAuth$ | async,
    domains: domains$ | async
} as state ">
    <span column-1 class="licence-name">
        {{state.user.role}}
    </span>
      <ul *ngFor="let domain in state.domains">
        <li>{{domain}}</li>
      </ul>
</ng-container>
Enter fullscreen mode Exit fullscreen mode

Hopefully, that will give you a bit help you avoid nested ngIf for observables suscription.

If you enjoyed this post, share it.

Discussion (1)

pic
Editor guide
Collapse
bezael profile image
Bezael Pérez

Congrats 👏