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:

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

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.

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

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s