💉 Shot #2: How to select Component or Directive in Angular template
Published in
1 min readApr 21, 2019
Introduction
There are a lot of use cases when you need to get a reference of a Component or Directive in Angular template to modify the entity properties or call it’s APIs.
Let’s assume we have a directive and component where directive applied:
Step 1: Use @ViewChild
to select instance of the Directive
With the magic of property decorator @ViewChild
, we can ask Angular to inject a reference to the MyDirective
in a property of our choice:
Step 2: 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: