ngOnInit Example | Angular

Last modified: April 22, 2019

ngOnChanges Example

ngOnInit Example

ngDoCheck Example

ngAfterContentInit Example

ngAfterContentChecked Example

ngAfterViewInit Example

ngAfterViewChecked Example

ngOnDestroy Example

home.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
  constructor() { }
  ngOnInit() {
    console.log("component has been initialized!")
  }
}

ngOnInit() executes once when a component is initialized.

ngOnInit() executes after data-bound properties are displayed and input properties are set.

ngOnInit() executes once after the first ngOnChanges.

When you create a new Angular component via the Angular CLI, the ngOnInit() method is included by default.

Notice how implements OnInit is added to the class definition. While not required, this is considered best practice as it provides the type checking benefits of TypeScript.

ngOnInit() will still execute regardless of whether or not implements OnInit is included in the class definition.

When should you use ngOnInit?

Use ngOnInit() whenever you want to execute code when the component is FIRST initialized. Remember that ngOnInit() only fires once after data-bound properties are set. This means ngOnInit() will execute if you refresh your browser or first initialize a component but not when other events occur.

You might also like: