interview community logo

1
0
Difference between constructor and ngOnInit
1 answer

What's the difference between constructor and ngOnInit?

Angular Robert Isaac asked 11 months ago


0

ngOnInit is An Angular lifecycle hook that is called after Angular has initialized all data-bound properties of a directive (including components).

use ngOnInit() method to handle any angular initialization tasks e.g. routing, Inputs, ... etc

use constructor is JS core feature, use it to initialize directive properties e.g. this.loading = false, ... etc

and there are two technical differences

  1. any input will be undefined in constructor
class FooComponent {
  @Input() data;
  constructor() {
    console.log(this.data); // will be undefined
  }

  ngOnInit() {
    console.log(this.data); // will have the value passed
  }
}
  1. in TypeScript strict mode, any property initialized inside ngOnInit will need to be optional or else will throw error
class FooComponent {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.form = this.formBuilder.group({});
  }
}

this example will throw TS2564: Property 'form' has no initializer and is not definitely assigned in the constructor. to avoid this it's either you move it to constructor or to declare it as form!: FormGroup;

Robert Isaac answered 11 months ago loading comments...