How to Handle Loading State in Angular: Simple and Effective
loading boolean variable in your component to track when data is being fetched. Show a loading indicator in the template with *ngIf while loading is true, and hide it when data is ready.Why This Happens
When fetching data asynchronously, the UI may try to display data before it arrives, causing empty or broken views. Without a loading state, users see nothing or stale content, which feels unresponsive.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user-list', template: ` <ul> <li *ngFor="let user of users">{{ user.name }}</li> </ul> ` }) export class UserListComponent implements OnInit { users: any[] = []; ngOnInit() { fetch('https://api.example.com/users') .then(response => response.json()) .then(data => this.users = data); } }
The Fix
Add a loading boolean to track when data is being fetched. Set it to true before starting the fetch and false after data arrives. Use *ngIf in the template to show a loading message or spinner while loading is true, and show the data list only when loading is false.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user-list', template: ` <div *ngIf="loading">Loading users...</div> <ul *ngIf="!loading"> <li *ngFor="let user of users">{{ user.name }}</li> </ul> ` }) export class UserListComponent implements OnInit { users: any[] = []; loading = false; ngOnInit() { this.loading = true; fetch('https://api.example.com/users') .then(response => response.json()) .then(data => { this.users = data; this.loading = false; }); } }
Prevention
Always initialize a loading state for async operations. Use Angular's async pipe with Observables for cleaner code and automatic subscription management. Keep UI feedback clear with spinners or messages. Use linting rules to enforce handling of async states.
Related Errors
Common related issues include:
- Not unsubscribing from Observables causing memory leaks.
- Showing stale data without refresh indication.
- UI freezing when loading state is not handled properly.
Fix these by using async pipe, managing subscriptions, and always toggling loading states.
Key Takeaways
loading variable to track data fetching state.*ngIf while data loads.loading to true before fetch and false after data arrives.async pipe with Observables for cleaner async handling.