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

--

--

Jawadhasan
Jawadhasan

Written by Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect

No responses yet