Simplifying Nested Async Subscriptions in Angular: A Practical Example

One way to subscribe 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>Using Object
The ng-contanier generate too noise into the DOM, but we can simplify using object into a single *ngIf and grouping each subscription 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>Hopefully, that will give you a bit to help you avoid nested *ngIf for an observable subscription.
If you enjoyed this post, share it.
Related Articles
Svelte for the First Time: A Personal Experience
Sometimes we want to learn something, just for fun or to build new side projects. I heard about Svelte in 2016, but never tried it until a few months ago with Bezael to create a small microfrontend. However, yesterday I started to build a small side ...
Maximizing Your Angular Build Performance with ESBUILD
ESBuild is a swift JavaScript compiler used for ViteJS. You can play with him in Angular, changing a single line in the angular.json file. Note: It is in experimental mode 😜 Change the builder from "@angular-devkit/build-angular:browser" to "@angula...
Real Software. Real Lessons.
I share the lessons I learned the hard way, so you can either avoid them or be ready when they happen.
Join 13,800+ developers and readers.
No spam ever. Unsubscribe at any time.