import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-sample', template: `<p>{{message}}</p>` }) export class SampleComponent implements OnInit { message = ''; ngOnInit() { this.message = 'Component initialized'; } }
The ngOnInit hook runs once after Angular sets up the component's input properties. It's the right place to perform initialization like fetching data or setting initial values.
The ngOnDestroy hook is called just before Angular destroys the component. It's the right place to clean up subscriptions and resources to prevent memory leaks.
import { Component } from '@angular/core'; @Component({ selector: 'app-test', template: `<p>Test</p>` }) export class TestComponent { ngOnInit() { console.log('Init'); } }
Implementing the OnInit interface is optional. Angular calls ngOnInit if it exists on the component class regardless of interface implementation.
import { Component, AfterViewInit, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', template: `<child-comp></child-comp>` }) export class DemoComponent implements OnInit, AfterViewInit { ngOnInit() { console.log('OnInit'); } ngAfterViewInit() { console.log('AfterViewInit'); } }
The ngAfterViewInit hook runs after Angular fully initializes the component's view and its child views. This always happens after ngOnInit, which runs earlier during initialization.
Lifecycle hooks let developers run code at key moments: ngOnInit to set up data or start processes, and ngOnDestroy to clean up subscriptions or timers. This careful management avoids memory leaks and keeps the app fast and stable.