Simplifying ViewChild and ContentChild in Angular

Read full article on the Infragistics blog

In this blog post, we will learn about ViewChild and ContentChild in Angular.

Essentially ViewChild and ContentChild are used for component communication in Angular. Therefore, if a parent component wants access of child component then it uses ViewChild or ContentChild.

Any component, directive, or element which is part of a template is ViewChild and any component or element which is projected in the template is ContentChild.

ViewChild and ViewChildren

If you want to access following inside the Parent Component, use @ViewChild decorator of Angular.

  1. Child Component
  2. Directive
  3. DOM Element

ViewChild returns the first element that matches the selector.

Let us assume that we have a component MessageComponent as shown in the below listing:

import { Component, Input } from '@angular/core';
selector: 'app-message',
template: `<h2>{{message}}</h2>`
export class MessageComponent {
@Input() message: string;

We are using MessageComponent inside AppComponent as shown in below listing:

import { Component, OnInit } from '@angular/core';
selector: 'app-root',
template: `
<app-message [message]='message'></app-message>
export class AppComponent implements OnInit {
message: any;
ngOnInit() {
this.message = 'Hello World !';

In application, you will get the output as below:

Here, MessageComponent has become child of AppComponent. Therefore, we can access it as a ViewChild. Definition of ViewChild is:

The Child Element which is located inside the component template”,

Here MessageComponent is located inside template of AppComponent, so it can be accessed as ViewChild.

export class AppComponent implements OnInit, AfterViewInit {
message: any;
@ViewChild(MessageComponent) messageViewChild: MessageComponent;
ngAfterViewInit() {
ngOnInit() {
this.message = 'Hello World !';

We need to do following tasks:

  • Import ViewChild and AfterViewInit from @angular/core
  • Implement AfterViewInit life cycle hook to component class
  • Create a variable with decorator @ViewChild
  • Access that inside ngAfterViewInit life cycle hook

In the output console you will find reference of MessageComponent, also if you can notice that __proto__ of MessageComponnet is set to Object.

Continue reading on the Infragistics blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at