ngOnInit Lifecycle Hook | ngOnInit Vs Constructor -Part 24

preview_player
Показать описание
This video is about Angular Lifecycle Hooks ngOnInit().
To learn Angular2 from scratch and for beginners Please see the link below:
#LifecycleHooks #ngOnInitVsConstructor

please read in detail about the angular lifecycle hooks on the below link:

In this tutorial, we discuss ngOnInit hook method.

Also, what is the difference between ngOnInit and Constructor and the advantages of using ngOnInit over the constructor?
We see with the example of how the lifecycle hook methods are working sequentially or which method is executed first or last.

Each interface has a single hook method whose name is the interface name prefixed with ng. For example, the OnInit interface has a hook method named ngOnInit() that Angular calls shortly after creating the component.

Constructor:
It is called only once in the lifecycle and before the ngOnInit() hook method.

ngOnInit()
Executes after the constructor and after ngOnChange hook for the first time. It is most commonly used for component initialization and retrieving data from a database.
Called once, after the first ngOnChanges().

* Use ngOnInit() for two main reasons:
-To perform complex initializations shortly after construction.
-To set up the component after Angular sets the input properties.

Example:

@Component({
selector: 'app-simple',
template: `
[p] You Entered: {{simpleInput}}[/p]
[div ]{{values}} [/div]
`,
styles: []
})
export class SimpleComponent implements OnChanges, OnInit {
@Input()
simpleInput: string;
values = '';

constructor() {
}

ngOnInit(): void {
// Called after the constructor, initializing input properties, and the first call to ngOnChanges.
// Add 'implements OnInit' to the class.
}

ngOnChanges(changes: SimpleChanges) {
// tslint:disable-next-line:forin
for (let propertyName in changes) {
let change = changes[propertyName];

}
}
}

So, When we run our application we see the output as:
-First, Constructor is called
- ngOnChanges Hook method is called
And at last, ngOnInit Hook method is called

This is actually a sequence of lifecycle works.

And suppose when we write the ngOnInit() before the constructor then this method is never called, only the constructor and ngOnChanges() will be called because lifecycle hook says ngOnInit is called after the constructor.

And when we run the application second time then only the ngOnChanges() method is called since constructor and ngOnInit() is called only once.
Рекомендации по теме