What Is Lifecycle hook?
Angular offers eight hooks to allow you to tap
into the lifecycle of directives and components as they are created, updated,
and destroyed.
Each has a single hook method with the name prefixed
ng. Stayed Informed - Angular 6 and 7
Angular calls these hook methods in the following
order -
1. ngOnChanges
– Called after input and output binding value changes.
2. ngOnInit
- Called once the components is
initialized.
3. ngDoCheck
- Called during every change detection.
4. ngAfterContentInit
- Called after component content initialized.
5. ngAfterContentChecked
- Called after every check of component
content.
6. ngAfterViewInit
- Called after a component's and child’s
views has been initialized.
7. ngAfterViewChecked
- Called every time the component's and child’s views has been checked.
8. ngOnDestroy
- Called just before the directive is destroyed.
The ngOnInit() and ngOnDestroy() methods play the
important roles in the real applications.
Use
of ngOnInit() –
There are two main reasons to Use of ngOnInit method
i.e.
1. The
ngOnInit method is used to perform the complex initializations shortly after
construction.
2. The
ngOnInit method is used to set up the component after Angular sets the input
properties.
Use
of OnDestroy() -
The OnDestroy method is used to clean-up logic
and it must run before Angular destroys the directive.
If you neglect to call the destroy method that
you may risk on memory leaks.