How to Use ngOnInit in Angular
As the creator of CoreUI and with over 25 years of Angular development experience, I’ll show you how to properly use the ngOnInit lifecycle hook for component initialization and data setup.
The ngOnInit lifecycle hook is called after Angular initializes the component’s data-bound properties and is the ideal place for component initialization logic and data fetching.
import { Component, OnInit, OnDestroy } from '@angular/core'
import { Subscription } from 'rxjs'
import { UserService } from './user.service'
import { DataService } from './data.service'
@Component({
  selector: 'app-user-dashboard',
  template: `
    <div>
      <h2>Welcome {{ user?.name }}</h2>
      <div *ngIf="loading">Loading...</div>
      <div *ngIf="error" class="error">{{ error }}</div>
      <div *ngIf="data?.length">
        <div *ngFor="let item of data">{{ item.title }}</div>
      </div>
    </div>
  `
})
export class UserDashboardComponent implements OnInit, OnDestroy {
  user: any
  data: any[] = []
  loading = false
  error: string | null = null
  private subscriptions = new Subscription()
  constructor(
    private userService: UserService,
    private dataService: DataService
  ) {
    // Constructor should only handle dependency injection
    console.log('Component constructed')
  }
  ngOnInit(): void {
    // Component initialization logic goes here
    console.log('Component initialized')
    // Fetch initial data
    this.loadUserData()
    this.loadDashboardData()
    // Set up subscriptions
    this.setupDataSubscriptions()
    // Initialize component state
    this.initializeComponentSettings()
  }
  private loadUserData(): void {
    this.loading = true
    const userSub = this.userService.getCurrentUser().subscribe({
      next: (user) => {
        this.user = user
        this.loading = false
      },
      error: (error) => {
        this.error = 'Failed to load user data'
        this.loading = false
        console.error('User loading error:', error)
      }
    })
    this.subscriptions.add(userSub)
  }
  private loadDashboardData(): void {
    const dataSub = this.dataService.getDashboardData().subscribe({
      next: (data) => {
        this.data = data
      },
      error: (error) => {
        this.error = 'Failed to load dashboard data'
        console.error('Data loading error:', error)
      }
    })
    this.subscriptions.add(dataSub)
  }
  private setupDataSubscriptions(): void {
    // Subscribe to real-time updates
    const updateSub = this.dataService.getDataUpdates().subscribe({
      next: (update) => {
        console.log('Data update received:', update)
        // Handle real-time updates
      }
    })
    this.subscriptions.add(updateSub)
  }
  private initializeComponentSettings(): void {
    // Set up component-specific configurations
    // Initialize form states, default values, etc.
  }
  ngOnDestroy(): void {
    // Clean up subscriptions to prevent memory leaks
    this.subscriptions.unsubscribe()
  }
}
Use ngOnInit for component initialization tasks like data fetching, setting up subscriptions, and configuring initial state. Avoid heavy logic in the constructor - use it only for dependency injection. ngOnInit is called after the component’s input properties are set, making it safe to access @Input values. Always implement OnDestroy to clean up subscriptions and prevent memory leaks. Use loading states and error handling for better user experience during data fetching.
Best Practice Note:
In CoreUI components, we consistently use ngOnInit for data initialization and component setup. This ensures our components load data efficiently and maintain proper lifecycle management, which is crucial for performance in complex dashboards and data-driven applications.
 Łukasz Holeczek
    Łukasz Holeczek
  



 
         
       
       
      