馃拤 Shot #1: How to select an element in Angular template
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: