Local references in templates

We have previously seen how we can bind data to our templates using data interpolation with the double curly braces syntax. Besides this, we will quite often spot named identifiers prefixed by a hash symbol (#) in the elements belonging to our components or even regular HTML controls. These reference identifiers, namely local names, are used to refer to the components flagged with them in our template views and then access them programmatically. They can also be used by components to refer to other elements in the virtual DOM and access its properties.

In the previous section, we saw how we could subscribe to the countdown progress through the progress event. But what if we could inspect the component in depth, or at least its public properties and methods, and read the value that the seconds property takes on each tick interval without having to listen to the progress event? Well, setting a local reference on the component itself will open the door to its public façade.

Let's flag the instance of our CountdownTimerComponent in the TimerComponent template with a local reference named #counter. From that very moment, we will be able to directly access the component's public properties, such as seconds, and even bind it in other locations of the template. This way, we do not even need to rely on the progress event emitter or the timeout class field, and we can even manipulate the value of such properties. This is shown in the following code:

@Component({
selector: 'timer',
template: `
<div class="container text-center">
<countdown-timer [seconds]="25"
(complete)="onCountdownCompleted()"
#counter >
</countdown-timer>
<p>
<button class="btn btn-default"
(click)="counter.seconds = 25">
reset
</button>
</p>
<p *ngIf="counter.seconds < 10">
Beware, only !
<strong>{{ counter.seconds }} seconds</strong>
</p>
</div>`
})
export class TimerComponent {
// timeout: any /* No longer required */
onCountdownCompleted(): void {
alert('Time up');
}
}
..................Content has been hidden....................

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