Using @ViewChild in Angular

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:

Like what you read? Give Nishu Goel a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.