[html] How to declare a variable in a template in Angular

Short answer which help to someone

  • Template Reference variable often reference to DOM element within a template.
  • Also reference to angular or web component and directive.
  • That means you can easily access the varible anywhere in a template

enter image description here

enter image description here

  • Declare reference variable using hash symbol(#)
  • Can able to pass a variable as a parameter on an event

enter image description here

  show(lastName: HTMLInputElement){
    this.fullName = this.nameInputRef.nativeElement.value + ' ' + lastName.value;
    this.ctx.fullName = this.fullName;
  }

*However, you can use ViewChild decorator to reference it inside your component.

import {ViewChild, ElementRef} from '@angular/core';

Reference firstNameInput variable inside Component

@ViewChild('firstNameInput') nameInputRef: ElementRef;

After that, you can use this.nameInputRef anywhere inside your Component.

Working with ng-template

In the case of ng-template, it is a little bit different because each template has its own set of input variables.

enter image description here

https://stackblitz.com/edit/angular-2-template-reference-variable