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:

app/user/user.component.tsimport { OnInit } from '@angular/core';

Next, you need to include the interface in the component class:

app/user/user.component.tsexport 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:

app/user/user.component.tsexport class UserComponent implements OnInit {
  constructor() {
    console.log('constructor is started');
  }
  ngOnInit() {
    console.log('onInit is applied');
  }
}
Задание 1

Make a private method show and call it when the component is initialized.