After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit
and ionViewWillLoad
.
If my understanding serves me right, ngOnInit
is an Angular lifecycle hook responsible for initializing directives and components. (Setting input properties of the directive/component.)
ionViewWillLoad
, on the other hand, is an Ionic navigation lifecycle event, which appears to run before the ionViewDidLoad
event that signifies everything has been loaded. Interestingly, it seems that the ionViewWillLoad
event has not been added to NavController, as indicated by the lack of documentation update.
As per my knowledge, the constructor is invoked by the JavaScript engine and should be steered away from complex initializations. (details: why you should avoid complex constructor logic)
Hence, I opted to utilize ionViewWillLoad
to configure the component after Ionic sets the input properties.
Interestingly, ionViewWillLoad
was the only event that functioned smoothly without any errors.
export class UsernamePage {
usernameControl: FormControl;
constructor(private userService: UserServiceProvider){ }
// No errors
ionViewWillLoad() { this.createUsernameForm(); }
// Errors
ionViewWillEnter() { this.createUsernameForm(); }
ionViewDidEnter() { this.createUsernameForm(); }
ionViewDidLoad() { this.createUsernameForm(); }
createUsernameForm() {
this.usernameControl = new FormControl('',
{
validators: [Validators.required, Validators.minLength(4)],
asyncValidators: CustomValidator.username(this.userService)
});
}
}
Should I continue using ionViewWillLoad
? Or would it be more beneficial to implement the OnInit interface? What sets them apart?