I want to have a loading screen before data is loaded. my data is collect from ngOnInIt and i want to make sure that the page will only show after data is loaded.
@if (!(dataReady$ | async)) {
<div class="spinner-overlay">
<app-loader/>
</div>
}
<hr>
<div>
<h1>something</h1>
<p>secondthing</p>
</div>
protected dataReady$ = new BehaviorSubject(false);
protected amountChange = signal(DetailsService.name);
I try setting a boolean inside the ngOnInIt but would not help as the HTML load first.
anscom ooi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can use the @if
and @else
to show a loading screen when the data is loading. I also use as
to store the async data in a property of the template to use. We can directly use the observable from the API call, to show the loading screen until the data is received.
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
@if ((data$ | async); as data) {
@for(row of data;track $index) {
<div>{{row.test}}</div>
}
} @else {
loading...
}
<hr>
<div>
<h1>something</h1>
<p>secondthing</p>
</div>
`,
})
export class App {
// below simulates a fake API call!
data$ = of([
{ test: 1 },
{ test: 2 },
{ test: 3 },
{ test: 4 },
{ test: 5 },
]).pipe(delay(3000));
}
bootstrapApplication(App);
Stackblitz Demo