0

I was following the tutorial Tour of Heroes. While adding a new hero they say

You can use an element paired with an add button.
Insert the following into the HeroesComponent template, after the heading:

<div>
  <label for="new-hero">Hero name: </label>
  <input id="new-hero" #heroName />

  <!-- (click) passes input value to add() and then clears the input -->
  <button type="button" class="add-button" (click)="add(heroName.value); heroName.value=''">
    Add hero
  </button>
</div>

Here I don't understand what is #heroName inside in input element (what is it called) and how does it help in pairing that input element with the button element.

Basically, what is that #<keyword> syntax within that input element. I know that it is not the id as that is already declared.

1 Answers1

0

To answer the question, it's a reference to the input. You can find more details here:

https://angular.io/guide/template-reference-variables

Template variables help you use data from one part of a template in another part of the template. Use template variables to perform tasks such as respond to user input or finely tune your application's forms.

In the tutorial context, it's a reference to the input element. It helps to pair it with a button to be able to access it's value, without having to actually define a variable in the component.ts and trying to update the template directly. This help you "skip" a step, and actually have direct access to that value.

Template reference variables can become very handy in certain cases and are commonly used for example in angular material ( to call a function for a component )

<mat-menu #menuComponent ...></mat-menu>
<button (click)="menuComponent.close()"></button>

In the above example, you bind the menuComponent variable to "mat-menu" component, in which case you can access all the variables, public methods of such. In that case we can call "close" method from the mat-menu component.

Let me know if this is still unclear and I can try to give you more examples and explanation

Ziyed
  • 491
  • 2
  • 12