DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Updated on

 

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

Oldest comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesnโ€™t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.