Using the @ViewChild decorator

The @ViewChild decorator instructs the Angular DI framework to search for some specific child component/directive/element in the component tree and inject it into the parent. This allows the parent component to interact with child components/element using the reference to the child, a new communication pattern!

In the preceding code, the audio element directive (the MyAudioDirective class) is injected into the WorkoutAudioComponent code.

To establish the context, let's recheck a view fragment from WorkoutAudioComponent:

    <audio #ticks="MyAudio" loop src="/static/audio/tick10s.mp3"></audio> 

Angular injects the directive (MyAudioDirective) into the WorkoutAudioComponent property: ticks. The search is done based on the selector passed to the @ViewChild decorator. Let's see the audio example again:

  @ViewChild('ticks') private ticks: MyAudioDirective;

The selector parameter on ViewChild can be a string value, in which case Angular searches for a matching template variable, as before.

Or it can be a type. This is valid and should inject an instance of MyAudioDirective:

@ViewChild(MyAudioDirective) private ticks: MyAudioDirective; 

However, it does not work in our case. Why? Because there are multiple MyAudioDirective directives declared in the WorkoutAudioComponent view, one for each of the <audio> tags. In such a scenario, the first match is injected. Not very useful. Passing the type selector would have worked if there was only one <audio> tag in the view!

Properties decorated with @ViewChild are sure to be set before the ngAfterViewInit event hook on the component is called. This implies such properties are null if accessed inside the constructor.

Angular also has a decorator to locate and inject multiple child components/directives: @ViewChildren.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.3.208