AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked In Angular

AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked In Angular

The life cycle hooks are AfterViewInit, AfterContentInit, AfterViewChecked, and AfterContentChecked. Angular raises them during a Component's lifecycle. In this article, we will discover what they are and when Angular uses them. We also discover the distinctions between AfterViewInit, AfterContentInit, AfterViewChecked, and AfterContentChecked.

Lifecycle hooks

When angular instantiates a component (or directive), the component's life begins.

Invoking the component's constructor and injecting the services via dependency injection are the first steps in the instantiation process.

When Angular creates a component, it initiates the component's change detection cycle. It initializes the component and checks and updates any data-bound input properties. The following life cycle hooks are then raised.

If Angular detects any changes to the Input property, it will fire the Onchanges event. It is called whenever angular detects a change in the input.

OnInit indicates that the component is ready to use. This hook allows us to run any initialization logic, change a few properties, and so on. This hook only executes once.

Because change detection may fail, we can use DoCheck to execute bespoke change detection.

Content Vs View

Before we go into these hooks, it's important to understand the difference between Content and View. AfterContentInit and AfterContentChecked are hooks that deal with content, while AfterViewInit and AfterViewChecked are hooks that deal with views.

Content

The external content injected into this component via Content Projection is referred to as content.

The HTML content is passed from the parent component to the child component using content projection. The template will be shown in a specific location by the child component. The ng-content element is used to create a spot in the child component's template, as seen below.

<h2>Child Component</h2>
<ng-content></ng-content>   <!-- place hodler for content from parent -->

The content is injected between the opening and closing elements by Parent. This content is passed to the child component by Angular.

<h1>Parent Component</h1>
<app-child> This <b>content</b> is injected from parent</app-child>

View

The term "view" refers to the component's template.

AfterContentInit

After the Component's content has been properly initialized and injected into the Components View, Angular executes the AfterContentInit life cycle hook.

Before raising this hook, Angular additionally updates the properties decorated with the ContentChild and ContentChildren.

Even if the component has no projected content, Angular calls this hook.

After the ngDoCheck hook, this hook fires.

Only fires once, during the initial change detection cycle, just after the component is created.

AfterContentChecked

AfterContentChecked is a life cycle hook that Angular runs after it has finished inspecting the content for changes during each change detection cycle.

Before raising this hook, Angular additionally updates the properties decorated with the ContentChild and ContentChildren.

After the ngDoCheck and AfterContentInit hooks, this hook fires.

AfterViewInit

After the component's view and its sibling views have been initialized, Angular executes this lifecycle hook during change detection.

Before raising this hook, Angular additionally modifies the properties decorated with the ViewChild and ViewChildren properties.

To handle any further initialization chores, use this hook.

Only fires once, during the initial change detection cycle, just after the component is created.

AfterViewChecked

After the change detector has checked a component's view and child views for modifications, Angular fires this lifecycle hook.

Before raising this hook, Angular additionally modifies the properties decorated with the ViewChild and ViewChildren properties.

Init Vs Checked

Init Hooks

When the content or view is initialized for the first time, Angular fires the AfterContentInit and AfterViewInit hooks. This happens during the initial change detection cycle, which angular starts right after the component is instantiated.

Checked Hooks

Angular checks if the content or view has changed by firing the AfterContentChecked and AfterViewChecked hooks. i.e. the prior displayed content or view is identical to the current rendered content or view.

Example
Now, using an example, let's look at the above hooks.

Add the following code under the child-component.ts:

import { Component } from "@angular/core";
 
@Component({
  selector: "app-child",
  template: `
    <div style="border:solid; border-width:1px;">
 
      <h2>Child Component</h2>
    
      message : <input [(ngModel)]="message">
 
      <p> Injected Content Below</p>
      <ng-content></ng-content>
 
    </div>
  `,
})
export class ChildComponent {
  message = "" 
 
  ngOnChanges() {
    console.log('  ChildComponent==>ngOnChanges');
  }
 
  ngOnInit() {
    console.log('  ChildComponent==>ngOnInit');
  }
 
  ngDoCheck() {
    console.log('  ChildComponent==>ngDoCheck');
  }
 
  ngAfterContentInit() {
    console.log('  ChildComponent==>ngAfterContentInit');
  }
 
  ngAfterContentChecked() {
    console.log('  ChildComponent==>ngAfterContentChecked');
  }
 
  ngAfterViewInit() {
    console.log('  ChildComponent==>AfterViewInit');
  }
 
   ngAfterViewChecked() {
    console.log('  ChildComponent==>AfterViewChecked');
  }
 
}

  1. Using ngModel, we have an input FORM element that is connected to the component's message attribute.
  2. <ng-content></ng-content> serves as a placeholder for the parent's injected content.
  3. for example whenever change detection invokes the hook, the component logs to console.Console.log(' ChildComponent==>ngOnChanges'); 

Add the following code under the app.component.ts:

import { Component, ViewChild } from "@angular/core";
import { ChildComponent } from "./child-component";
 
@Component({
  selector: "my-app",
  template: `
  
  AfterConentInit, AfterContentChecked, AfterViewInit, AfterViewChecked
 
  <app-child>
    <b>Injected</b> content from the <i>Parent</i>
  </app-child>
 
 
 
  `,
})
export class AppComponent {
 
  message="";
 
  @ViewChild(ChildComponent) viewChild: ChildComponent;
 
  ngOnChanges() {
    console.log('AppComponent==>ngOnChanges');
  }
 
  ngOnInit() {
    console.log('AppComponent==>ngOnInit');
  }
 
  ngDoCheck() {
    console.log('AppComponent==>ngDoCheck');
  }
 
  ngAfterContentInit() {
    console.log('AppComponent==>ngAfterContentInit');
  }
 
  ngAfterContentChecked() {
    console.log('AppComponent==>ngAfterContentChecked');
  }
 
  ngAfterViewInit() {
    console.log('AppComponent==>AfterViewInit');
  }
 
  ngAfterViewChecked() {
    console.log('AppComponent==>AfterViewChecked');
    this.message=this.viewChild.message;
  }
 
}

  1. By placing the <b>Injected/<b> content from the <i>Parent</i> within the element tag, we are injecting material into <app-child>.
  2. To update the reference to the child component in the property ChildComponent, use the ViewChild query.
  3. this.message=this.viewChild.message; this component's message property is updated with that of ChildComponent

Now let's check what occurs when we execute this app.

On Component Creation

The hooks are fired in the following order during component construction.
  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
  6. AfterViewInit
  7. AfterViewChecked

AfterContentInit, AfterContentChecked, AfterViewInit and AfterViewChecked during application startup in angular


On the application run, Angular performs change detection twice. Consequently, the

On Component Running

Angular does not fire the init hooks once the component has been initialized. Only the hooks that have been checked are used.
  1. DoCheck
  2. AfterContentChecked
  3. AfterViewChecked

Content is first

Before the components view and child views, Angular initializes and checks the content.

AfterViewInit & AfterViewChecked fires after child components are ready

Angular initializes the component's view after the content. It also sets up the child's views and executes the change detection for them. As a result, the current component and all of its descendants are ready to render by the time we receive the hooks AfterViewInit and AfterViewChecked.

Init Hook fires only once

Init hooks only fire once, during the initial change detection cycle, which happens just after the component is created. As a result, it's the perfect area to perform custom startup logic. For content-related initializations, use AfertContentInit, and for view-related initializations, use AfterViewInit.

Avoid using Checked Hooks

Every change detection cycle includes a check for checked hooks. When you simply click on the input element and walk away, for example.

As a result, it is preferable to avoid using these hooks. If you decide to use these hooks, make sure your code is as small as possible; otherwise, the application may slow down.

Do not modify bindings in Checked Hooks

Open the app.component.ts ngAfterViewChecked function. we assign the value of viewChild.message to the parent component's message variable. There are no errors in the code.

ngAfterViewChecked() {
  console.log('AppComponent==>AfterViewChecked');
  this.message=this.viewChild.message;
}

Now add the following to the app.component.ts template.

message from child {{message}}

and run the application.

Modifying the binding in AfterViewChecked hook-in angular

There are two key elements to keep in mind here.
  1. Before refreshing the message in app.component.ts, it waits for a tick.
  2. ExpressionChangedAfterItHasBeenCheckedError

Despite the fact that the code appears to be in good shape, this is what happens.
  1. The value of the message is initially null.
  2. In the input element, we type h. A change detection cycle is started as a result of this.
  3. It examines the message variable's value. Its value is null. As a result, the DOM is updated with an empty string.
  4. The AfterViewChecked hook is fired by Angular.
  5. The message variable is changed to h.
  6. Angular then does the last check to ensure that all of the binding values are valid. If it detects that the message value is now h, it is not the same as when it examined it in step 3. The ExpressionChangedAfterItHasBeenCheckedError is raised.
  7. The change detection cycle comes to an end.

As you can see, h is not changed in the DOM at the end of change detection.
  • In the input element, we type e.
  • The cycle of change detection begins.
  • It examines the message variable's value. It has the value of h. As a result, Angular uses h to update the DOM.
  • The AfterViewChecked hook is fired by Angular.
  • The message variable is changed to him.
  • Angular then does the last check to ensure that all of the binding values are valid. If it detects that the message value is now h, it is not the same as when it examined it in step 3. The ExpressionChangedAfterItHasBeenCheckedError is raised.
  • The change detection cycle comes to an end.

Only in development mode does step 6 occur. If any changes are detected, Angular just checks the bindings and does not update the DOM. It merely adds to the problem.

Conclusion

In this article, we learned what is AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked and when Angular uses them. We also learned the distinctions between AfterViewInit, AfterContentInit, AfterViewChecked, and AfterContentChecked.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post