0
0
AngularDebug / FixBeginner · 4 min read

How to Handle Loading State in Angular: Simple and Effective

In Angular, handle loading state by using a 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.

typescript
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);
  }
}
Output
<ul></ul> (empty list shown before data loads)
🔧

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.

typescript
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;
      });
  }
}
Output
Loading users... (shown while fetching) <ul><li>User 1</li><li>User 2</li>...</ul> (shown after data loads)
🛡️

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

Use a boolean loading variable to track data fetching state.
Show a loading indicator with *ngIf while data loads.
Set loading to true before fetch and false after data arrives.
Prefer Angular async pipe with Observables for cleaner async handling.
Always provide clear UI feedback to improve user experience during loading.