The ngOnInit hook in Angular
The ngOnInit hook is triggered when the component is initialized. It works similarly to a class constructor, but it can perform more complex tasks, such as loading data from the server.
Let's see how to use this hook. First, we need to import its interface:
import { OnInit } from '@angular/core';
Next, you need to include the interface in the component class:
export class UserComponent implements OnInit {
}
After that, we can write the ngOnInit method in the component class and this method will be executed automatically when the class is initialized. Let's check its operation:
export class UserComponent implements OnInit {
constructor() {
console.log('constructor is started');
}
ngOnInit() {
console.log('onInit is applied');
}
}
Make a private method show and call it when the component is initialized.