Understand ViewChild in Angular 2 and Angular 4

Download Source Code For This Lab

Source Code

Before Getting Started…..

Let's talk about the concept of parent and child not in the context of programming but in general

A Parent may need to access the property of a child to perform family duties or get certain things done so he must have a key or way to get into the child's room.

The Concept of ViewChild follows the same principle.

What is ViewChild and why do we need it in Angular?

Components are one of the most crucial parts of Angular.

When we are writing our application in angular we have a root component and several child component which form a tree like structure in angular.

The @ViewChild decorator is used to gain access to a Child component so that root component or Parent Component can access its Method and Properties.

How do I use @ViewChild decorator in my Application?

Simple @ViewChild decorator function takes the name of the child component class and automatically finds the child component selector in the parent component template and binds it to the parent template.

We can also use template reference variable as input for Viewchild decorator function.

Now let's look at the Code for the Child Component which is to be accessed

Here app-child is the selector for the child component.

Here we will use the Child Component name as input for @ViewChild Decorator function.

Now in the Parent or Root AppComponent.ts

As you can see we have passed the Child Component class name as input the @Viewchild function in AppComponent class.

Below it we have written a ShowChild() function which will access the child component and call the show function which will in turn display the child component template.

Special thing here the <app-child> selector in the parent component template automatically references the app-child selector in its respective component and helps in accessing the child components.

Here is AppModule.ts for Reference

In Conclusion….

We can say that @ViewChild decorator provides us with a easy and simple way to access and manipulate the properties and methods of a Child Component from a container or root component.

Download Source Code For This Lab

Source Code

+91 9967590707
questpond@questpond.com / questpond@yahoo.com