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:

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:


Leave a comment

Your email address will not be published. Required fields are marked *