ANGULAR LIFECYCLE HOOKS
Overview
Lifecycle hooks are a special functionality and timed methods in Angular that allow us to hook into and run code at a specific lifecycle event of a component or directive.
Angular manages components and directives? ?when it creates, updates or destroys them. With lifecycle hooks, So that we can gain better control of our application.
For doing this We add some specific hook methods prefixed with ng to our component or directive. These hooks are split into two types:
- Hooks for components or directives
- Hooks for child components
Following are lifecycle hooks.
- ngOnChanges
When we change the value of data which is a bind property, that time this method is called.
For Implements in the application
- ngOnInit
It is called after Angular has initialized all data-bound properties of a directive and after the first ngOnChanges call.
ngOnInit() is still called even when ngOnChanges() is not, which is the case when there are no template-bound inputs.
For Implements in the application
- ngDoCheck
DoCheck is a callback method, this performs change detection, this is invoked after the default change detector runs. This hook comes after the OnInit hook.
DoCheck invokes a custom change function for a directive, in addition to the check performed by the default change.
For Implements in the application
- ngAfterContentInit
it is called in response after Angular projects external content into the component’s view.
content is the component and directives that are projected in between the <ng-content></ng-content> tag.
For Implements in the application
- ngAfterContentChecked
ngAfterContentChecked() is a callback method which will get called by Angular immediately after the default change detector completes checking all of the directive’s content.
And ngAfterContentChecked() lifecycle hook will get called after the following lifecycle is invoked.
- ngOnChanges()
- ngOnInit()
- ngDoCheck()
- ngAfterContentInit()
- ngAfterContentChecked()
- ngAfterViewInit
ngAfterViewInit() fires once after the view DOM finishes initializing. The view always loads right after the content. ngAfterViewInit waits on @ViewChild(ren) queries to resolve. These elements are queried from within the same view of the component.
- ngAfterViewChecked
ngAfterViewInit() hook gets called after the content and the child component view gets in and is called after ngAfterViewInit() and ngAfterContentChecked() whenever the content is being changed.
- ngOnDestroy
ngOnDestroy() This hook gets called before the component is getting off the DOM. Unsubscribe every subscription and clear every interval to prevent memory leaks.