Angular — ViewChild and TemplateReference Variable

Jawadhasan
4 min readOct 4, 2023
Photo by Anastasiia Kamil on Unsplash

Introduction

In earlier post, we saw how to communicate in and out of components using input/output properties.

In this post we’ll explore another way to access the public properties and methods of a child components. This could be useful for different use cases.

We’ll learn about using Template Reference Variable and/or @ViewChild() decorator.

ViewChild/ViewChildren Selector

A component, can obtain a reference to an element or directive on its template and access it directly.

We can use ViewChild/ViewChildren directives to communicate b/w component and its template.

Selector can be

  • Element e.g. Template Reference variable / ElementRef
  • NgModel
  • Custom-directive/child component

ElementRef

Following example shows how to get reference to div element using ViewChild decorator. Notice that the div is referenced using #divElementRef variable and it is used as a selector for ViewChild decorator.

NgModel

In the following example ViewChild is used with NgModel

Custom-Directive/Child component

The following is the example of referencing a custom directive using ViewChild

Once we have the reference, we can use it as per the requirements.

ViewChild and NativeDomElement

The following example shows that once we have hold of the reference, we can use nativeElement for calling methods or in case of template, its methods or properties can be accessed.

Lets see few more examples next.

Template Reference Variables

Template Reference Variables allows us to specify a local variable name, that points to a component, and then we can access any public properties or methods on that component using that…

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect