Lifecycle Hooks in Angular
→ In Angular, a lifecycle hook is a predefined method that allows us to tap into certain moments of a component’s lifecycle. These methods are called a hooks because they allows us to “hook into” a particular moment of a component’s lifecycle and perform some action or logic.
ngOnInit:
→ It is a method that is called after the component is initialized and before it is rendered on the screen.
→ It is a lifecycle hook that is very useful to perform any necessary setup like fetching the data from the API before the component is displayed to the user.
→ This method is called only once. It cannot be triggered again.
→ ngOnInit is called right after the constructor method.
→ This is one of the most used lifecycle hooks in angular and also it is automatically added into the component when we generate a component using angular cli.
ngOnChanges:
→ This lifecycle method will be called only when it detects a change in input property present in the child component that is passed from the parent component.
→ Without an input property present, this lifecycle hook will never work.
→ ngOnChanges is the only lifecycle hook that takes a parameter of type SimpleChanges. No other lifecycle hook in Angular will take a parameter.
→ But this method will fail to trigger when there is a change in an array or an object occurs. But in these cases, ngDoCheck can be used, which runs each time when it detects a change in the input property.
→ The ngOnChanges will run before the ngOnInit method.
parent-component:
In this parent component we are having a child component app-child. We send a property ‘name’ as an input to the child component. And, we update the value of the ‘name’ property in the onTyping method. Now the value will be updated whenever the focus of the input element changes to blur.
child-component:
In the child-component we are receiving the input ‘name’ using the @Input decorator.
Now the result will be,
If the value of the input property “name” changes, then it will triggered again.
We can also access the previous and current value using this method.
ngDoCheck:
→ This is used when the ngOnChanges fails to detect changes in areas like objects or arrays.
→ ngOnChanges uses the default change detection mechanism of angular which can fail in some areas and it is triggered only when the value of the input property changes.
→ The ngDoCheck detects the changes in the components internal state.
→ For example, ngOnChanges will not be triggered if the value of some array that we have in our component changes. But, ngDoCheck can even detect this small change.
→ But we need to be very careful in using ngDoCheck since it has a huge effect in application’s performance as it will be triggered more frequently.
ngAfterContentInit:
→ To Understand this, we should have the knowledge about ViewChild and ContentChild decorators.
@ViewChild:
→ The ViewChild is a decorator in angular that is used to access the native DOM element that has a template reference variable.
→ Template reference variable is recognized by the hash# symbol in the HTML element.
→ Similarly we have @ViewChildren which is the plural form of the @ViewChild which means, we can access multiple html elements having the same template reference variable.
@ContentChild:
→ In angular, it is possible to send a html element as an input to the child component same like how we are sending some data through property binding.
→ And, we can use this html element in the child component’s html by using a special directive <ng-content></ng-content>.
→ This is basically a router outlet for the html element that we pass as an input to the child component.
→ We also have the @ContentChildren same like the @ViewChildren.
Here, <app-viewchild> is a component that is the children of some parent component. We are passing a h4 element having a template reference variable #content to the child component.
Now we cannot access this h4 element using ViewChild decorator in the app-viewchild component. To access this h4 element we must use the ContentChild decorator.
Now coming to afterContentInit,
Here we are projecting a content by passing a html element h3 inside the child component with a template reference variable #projectedElement.
We are catching the projected content by using the ng-content directive in the child component.
In the child component we can access the element only by using the ContentChild decorator.
And, we can access this element only under the ngAfterContentInit() lifecycle hook. If we try to access this in any other lifecycle hook or method, it won’t work.
If we try to access it with ngOnInit or any other method, the result will be undefined.
ngAfterContentChecked:
→ If any changes occurs in the projected content, this lifecycle hook method will be triggered.
→ For ex, we may have set a style attribute with color property to the projected h3 element and the value of the color property is bound to an input box, and if we type some color in the input box, so that the color changes, here a change is detected by the angular.
→ Likewise, whenever a change is detected the ngAfterContentChecked will run.
→ The important point to note is the ngAfterContentInit will run only once. But the ngAfterContentChecked will run whenever a change is detected.
→ So, basically ngAfterContentInit and ngAfterContentChecked is used only under the projected content concept. If we don’t have a projected content in our project, then there is no point in using this lifecycle hook and this lifecycle hook method will never be triggered also.
ngAfterViewInit:
→ It is similar to the ngAfterContentInit.
→ This lifecycle hook is used only when we use a @ViewChild decorator .
→ As we saw before, the ViewChild decorator is used to access the native DOM element. We use a template reference variable to identify the HTML element.
→ The element that we are trying to access using a ViewChild decorator can be accessed in the ngAfterViewInit method.
→ This lifecycle hook method will run only once same like the ngAfterContentInit.
Here we are logging the element in the ngAfterViewInit method.
In the above image we can see the element has been logged in the console.
But what if we try to access this element in the ngOnInit method?
→ It will be logged as undefined, since the element is not yet initialized.
ngAfterViewChecked:
→ It is similar to the ngAfterContentChecked method.
→ If any change detection is found in that particular element by angular, this method will be triggered.
→ Since, ngAfterViewInit will be triggered only once during the initialization, this method will be very useful in detecting changes and further operations to the particular element.
ngOnDestroy:
→ This method will be triggered when a component destroys.
→ If a user switches to another route, the view will be changed from one component to another component. At that time, a component will be destroyed and another component will be rendered.
→ So, when a component is destroyed this lifecycle hook method will be triggered.
→ It is the exact opposite of ngOnInit.
→ This method will be triggered only once like the ngOnInit.
Order:
This is the order in which all the lifecycle hook methods will be triggered if all these methods are called in a class.
Constructor:
→ A constructor is a special method in a class that gets called when a class is instantiated using the ‘new’ keyword and it is used to initialize objects.
→ When we create an instance of a class, the constructor is called automatically to set up the object with initial values.
Ex:
class person {
name: string;
age: number;
constructor (){
this.name = name;
this.age = age;
}
}
// Instantiating the class car:
let newPerson = new person('Sanjay', 22);
→ But in Angular, the constructor is used to inject dependencies into a component or service.
→ When a component or service is created, Angular’s dependency injection system automatically provides the instances of the requested services to the component so that we can use the properties and methods of the service that we have injected into our component.
→ The constructor method is called before the Angular’s ngOnInit lifecycle hook.