Home > Mobile >  Angular - ngIf condition displays both the data on Initial render
Angular - ngIf condition displays both the data on Initial render

Time:02-19

In my Angular project where I get data from API and display on frontend. I am using ngIf to display data, if no data is available then elseNotDone is displayed.

The problem I am facing is when component reloads, I first see No Data available for few milliseconds and then data is displayed

How can I make sure else condition is not displayed on initial render?

<section *ngIf="data!== undefined && data.length > 0; else elseNotDone">
  <h2>Amazon Data</h2>
  <div>
  // display data from API
  </div>
</section>
  <ng-template #elseNotDone>
  No Data available
  </ng-template>

CodePudding user response:

This is because the component initializes before the data has arrived. Once the data arrives, the component can then use it.

I would highly recommend learning about Angular Resolvers that prevent the component from initializing before the data is available. This allows you to implement things like loaders / spinners / etc, that appear while the data is being fetched.

EDIT: From the Angular documentation: https://angular.io/api/router/Resolve

CodePudding user response:

Unnecessarily you complicated it:

*ngIf="data !== undefined && data.length > 0; else elseNotDone"

Change it to:

*ngIf="data && data.length > 0; else elseNotDone"

For your main problem: Create a variable isLoaded and wrap your code in it:

<div *ngIf="isLoaded">
  .... your code...
</div>

It will solve your problem to show anything until data is loaded.

  • Related