Using @ViewChild in Angular

Nishu Goel
Sep 8, 2018 · 2 min read

A ViewChild is a component, directive, or element as a part of a template. If we want to access a child component, directive, DOM element inside the parent component, we use the decorator @ViewChild() in Angular.

To understand this, suppose we have two components, a child and a parent one. Since the child component can be located inside the parent component, it can accessed as @ViewChild.

In the above code, we imported @ViewChild decorator and then imported the lifecycle hook AfterViewInit and implemented it. Now, to change the property value, we can make use of the viewchild we just create like:

ngAfterViewInit(){
this.chviewChild.message = ‘Changed value of View Child’
}

This will output the value Changed value of View Child, but will throw an error saying “Expression has changed after it was last checked”.

To handle this error, we use Change detection using ChangeDetectorRef

Here, we have imported ChangeDetectorRef from ‘@angular/core’ and injected it to the constructor. We have also called the method detectChanges().

This was for one child element located inside the component template, but what in the case when we have multiple references to the child element?
That is when @ViewChildren comes into play.

Modifying the template,

Finally, marking the reference of ViewChildren with type QueryList,

Now, we can update the value of the message property using Viewchildren inside the ngAfterViewinit() life cycle hook like this:

this.chviewChildren.forEach((item) => {item.message = ‘Updated Value’;});

Let us look at the final code now:

This gives us the output as:

Nishu Goel

Developer@UI Garage, IBM, Angular, Author — https://amzn.to/2Zd9ADd

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade