Understanding template reference variables

Template reference variables are created on the view template and are mostly consumed from the view. As you have already learned, these variables can be identified by the # prefix used to declare them.

One of the greatest benefits of template variables is that they facilitate cross-component communication at the view template level. Once declared, such variables can be referenced by sibling elements/components and their children. Check out the following snippet:

    <input #emailId type="email">Email to {{emailId.value}} 
    <button (click)= "MailUser(emaild.value)">Send</button> 

This snippet declares a template variable, emailId, and then references it in the interpolation and the button click expression.

The Angular templating engine assigns the DOM object for input (an instance of HTMLInputElement) to the emailId variable. Since the variable is available across siblings, we use it in a button's click expression.

Template variables work with components too. We can easily do this:

    <trainer-app> 
     <workout-runner #runner></workout-runner> 
     <button (click)= "runner.start()">Start Workout</button> 
    </trainer-app> 

In this case, runner has a reference to the WorkoutRunnerComponent object, and the button is used to start the workout.

The   ref-  prefix is the canonical alternative to   #. The   #runner  variable can also be declared as   ref-runner.