What's the difference between constructor
and ngOnInit
?
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
class FooComponent {
@Input() data;
constructor() {
console.log(this.data); // will be undefined
}
ngOnInit() {
console.log(this.data); // will have the value passed
}
}
ngOnInit
will need to be optional or else will throw errorclass 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;