TIL: ngIf can also have an else clause in Angular

prayatna

Prayatna Bhattarai

Posted on October 28, 2020

TIL: ngIf can also have an else clause in Angular

I have a message component that makes an async call to retrieve the message. In my template, I use the async pipe to populate the view. So on the component, I have a message$ that gets the message from a service like so:

message$ = this.messageService.getMessage();
Enter fullscreen mode Exit fullscreen mode

and in my message-component.html I have

<div *ngIf="message$ | async as message">
      {{message.value}}
</div>
-- other code
Enter fullscreen mode Exit fullscreen mode

But the issue here is, I don't want my view to be empty when the message is being retrieved. I can use the else clause inside the *ngIf statement and define a template that replaces the div from above to show that something is loading. You can use a loading spinner or something similar, but for simplicity, I will just use a div with a text. So my final view will be something like

message.component.html

<div *ngIf="message$ | async as message; else isBusy">
  {{message.value}}
</div>
<ng-template #isBusy>Loading...</ng-template>
Enter fullscreen mode Exit fullscreen mode

And that's it; hope that helps.

PS: The method stated above may not always be the best way to show a loading spinner for an async call, if there is any better way of doing it please let me know. TIA

πŸ’– πŸ’ͺ πŸ™… 🚩
prayatna
Prayatna Bhattarai

Posted on October 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related