ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular

AfterViewInit, AfterContentInit, AfterViewChecked & AfterContentChecked are the life cycle hooks. Angular raise them during the lifecycle of a Component. In this tutorial, we will learn what are they and when Angular invokes them. We also learn the difference between the AfterViewInit Vs AfterContentInit Vs AfterViewChecked & AfterContentChecked.

Lifecycle hooks recap

The life of a component (or directive) starts, when angular instantiates the component.

Instantiation starts with invoking the component’s constructor and injecting the services via dependency injection.

Once the Angular instantiates the component, it starts the change detection cycle for the component. It checks & updates any data-bound input property of the component & Initializes the component. It then raises the following life cycle hooks.

Onchanges, if Angular detects any changes to the Input property. It runs every time angular detects an input change.

OnInit, which tells us that the component is ready. This hook gives us a chance to run any initialization logic, updates a few properties, etc. This hook runs only once.

DoCheck which allows us to run custom change detection because change detection may overlook some of the changes. This hook runs during every change detection cycle.

After this angular invokes four more hooks. They are AfterContentInit, AfterContentChecked, AfterViewInit & AfterViewChecked. We will look at them in detail.

Finally, when we remove the component, Angular invokes the ngOnDestroy hook and then destroys the component.

Content Vs View

Before diving into these hooks, we need to know the difference between Content & View. The hooks AfterConentInit & AfterContentChecked deals with the Content, While AfterViewInit, AfterViewChecked deals with the View.

Content

Content refers to the external content injected into this component using the Content Projection.

Content projection is a way to pass the HTML content from the parent component to the child component. The child component will display the template in a designated spot. We use the ng-content element to create a spot in the template of the child component as shown below.

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

Parent injects the content between the opening & closing element. Angular passes this content to the child component.

                              

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

View

View refer to the the template of the component.

AfterContentInit

The AfterContentInit is the Life cycle hook that angular calls after the Component’s content has been fully initialized and injected into Components View.

Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook.

Angular calls this hook even if there is no projected content in the component

This hook fires after the ngDoCheck hook.

Fires only once, during the first change detection cycle, immediately after the creation of the component.

AfterContentChecked

AfterContentChecked is the life cycle hook, that angular calls during every change detection cycle after Angular completes the checking of the content for changes.

Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook.

This hook fires after the ngDoCheck & AfterContentInit.

AfterViewInit

A lifecycle hook that Angular calls during the change detection after it completes initialization of component’s view and its child views.

Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.

Use this hook to handle any additional initialization tasks.

Fires only once, during the first change detection cycle, immediately after the creation of the component.

AfterViewInit

A lifecycle hook that Angular calls after the change detector completes the checking of a component’s view and child views for changes.

Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.

Once, we have reference to the DOM Element, we can use the renderor2 to manipulate its styles etc.

Init Vs Checked

Init Hooks

Angular fires the AfterContentInit & AfterViewInit hooks, when the content or view is initialized for the first time. That happens during the first change detection cycle, which angular invokes immediately after the instantiation of the component.

Checked Hooks

Angular fires the AfterContentChecked & AfterViewChecked hooks, where Angular checks if the the content or view has changed. i.e previously rendered content or view is same as the current content or view.

Example

Now, now let use see above hooks using an example

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. We have a input FORM element, which is bound to message property of the component using ngModel
  2. <ng-content> <ng-content> is a place holder for the injected content from the parent.
  3. The code ex: console.log(' ChildComponent==>ngOnChanges'); in the component logs to console, whenever change detection invokes the hook;
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. We are injecting the content to <app-child> by placing the content Injected content from the Parent within the element tag.
  2. Using ViewChild query to update the reference to the child component in the property ChildComponent
  3. this.message=this.viewChild.message; updates the message property of this component with that of ChildComponent

Now let us run this app and see what happens.

On Component Creation

On the component creation, the hooks are fired in the following order.

  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
  6. AfterViewInit
  7. AfterViewChecked
image

Angular runs the change detection twice on application startup. Hence, the

On Component Running

Once the component is initialized, Angular do not fire the init hooks. Only the the checked hooks are invoked.

  1. DoCheck
  2. AfterContentChecked
  3. AfterViewChecked

Content is first

Angular initializes and checks the content first, before the components view & child views.

AfterViewInit & AfterViewChecked fires after child components are ready

After content, angular initializes the components view. It also initializes the child views & runs thier change detection. Hence, by the time we receive the hooks AfterViewInit & AfterViewChecked, the current component & all its children are ready to render.

Init Hook fires only once

Init hooks fires only once, during the first change detection cycle, which angular fires immediately after the creation of the component. This makes it best place to run some custom initialization logic. Use the AfertContentInit for content related initialization & AfterViewInit for view related initializations.

Avoid using Checked Hooks

Checked hooks runs on every change detection cycle. For example when you just click on the input element and move away.

Hence it is better to avoid using these hooks. If you choose to implement these hooks then ensure that your code is extremely lightweight otherwise it may slow down the application.

Do not modify bindings in Checked Hooks

Read Token

Open the ngAfterViewChecked method of the app.component.ts. here, we assign value of the viewChild.message to the message variable of parent component. Code does not raise any errors.

                              

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

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

                              

message from child {{message}}
                            
                        

and run the app.

There are two important points to note here.

  1. The {{message}} in the app.component.ts waits a tick before updating
  2. ExpressionChangedAfterItHasBeenCheckedError

Although the code looks fine, but this is what happens

  1. Initially the value of message is empty
  2. We enter h in input element. This starts a change detection cycle.
  3. It checks the value of message variable. Its value is empty. Hence updates the DOM with empty string.
  4. Angular fires the AfterViewChecked hook
  5. We update the message variable to h.
  6. Angular runs another check to see if all the bindings values are correct. If detects message value is now h is different from when it checked it in the step 3. It raises the ExpressionChangedAfterItHasBeenCheckedError
  7. Change detection cycle ends.

Now, as you can see at the end of change detection h is not updated in DOM.

  1. We, type e in input element.
  2. A change detection cycle starts
  3. It checks the value of message variable. Its value is h. Hence Angular updates the DOM with h.
  4. Angular fires the AfterViewChecked hook
  5. We update the message variable to he.
  6. Angular runs another check to see if all the bindings values are correct. If detects message value is now h is different from when it checked it in the step 3. It raises the ExpressionChangedAfterItHasBeenCheckedError.
  7. Change detection cycle ends.

The step 6 only happens only in development mode. Angular only checks the bindings, but does not update the DOM if it detects any changes. It only raises the error.