馃拤 Shot #1: How to select an element in Angular template

Nikita Poltoratsky
Angular Shots
Published in
1 min readApr 20, 2019

Introduction

There are a lot of use cases when you need to get a reference of an element in Angular template to modify the element properties or call native APIs.

Let鈥檚 assume we have a component:

Step 1: Add template reference variable to the element

In Angular templates, we have the so-called template reference variable we can assign to get references to elements:

Step 2: Use @ViewChild to select the element

With the magic of property decorator @ViewChild, we can ask Angular to inject a reference to the element in a property of our choice:

Step 3: Use the reference

The reference will be available in the ngAfterViewInit hook, since we need to wait until the template is actually rendered to obtain the reference.

Shot

And here is the final shot ready for injection:

Useful Links

  1. @ViewChild property decorator
  2. Template expression context

--

--

Nikita Poltoratsky
Angular Shots

Developer Advocate at Akveo 路 Tech Author 路 Nebular and Ngx-Admin team 路 Minsk, Belarus