angular tutorials

Angular – Access template reference variables from component class ?

This tutorial guides you on how to access template reference variables from component class in Angular. A template reference variable is nothing but a reference to a DOM element within a template. Let’s see how to use local references in templates and access them from component class with example.

Angular – Access template reference variables from component class

To declare a reference variable in a template, you need to use hash symbol (#) as shown below. The reference variable “#itemNameInput” declares a itemNameInput variable on an <input> element.

<input 
    type="text" 
    class="form-control" 
    #itemNameInput">

Let’s take the following Two-way Data Binding example angular code and try to use local references or template reference variables in the template instead of two-way data binding.

create-item.component.html

<div class="row">
    <div class="col-xs-12">
      <p>Create Items and Specifications!</p>
      <label>Item Name</label>
      <input type="text" class="form-control" [(ngModel)]="newItemName">
      <label>Item Description</label>
      <input type="text" class="form-control" [(ngModel)]="newItemDesc">
      <br>
      <button
        class="btn btn-primary"
        (click)="onAddItem()">Add Item</button>
      <button
        class="btn btn-primary"
        (click)="onAddItemSpec()">Add Item Specifications</button>
    </div>
  </div>

create-item.component.ts

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css']
})
export class CreateItemComponent implements OnInit {
  ---
  ---
  ---

  constructor() { }

  ngOnInit(): void {
  }

  onAddItem() {
    this.itemAdded.emit({
        itemTitle: this.newItemName, 
        itemDesc: this.newItemDesc
    });
  }

  onAddItemSpec() {
    this.itemSpecAdded.emit({
      itemTitle: this.newItemName, 
      itemSpec: this.newItemSpec
    });
  }

}

Note, when you refer to the template, here we just wanted to save or use the data only when we are clicking the buttons “Add Item” or “Add Item Specifications”. Therefore, it would be just enough to get the value of the input element at that point of time. To achieve this we can use local references or template reference variables.

Let’s try to change the implementation wrt to first input element “Item Name” and button “Add Item” by using template reference variables as shown below. The modified code should look like below.

create-item.component.html

<div class="row">
    <div class="col-xs-12">
      <p>Create Items and Specifications!</p>
      <label>Item Name</label>
      <!-- <input type="text" class="form-control" [(ngModel)]="newItemName"> -->
      <input 
          type="text" 
          class="form-control" 
          #itemNameInput>
      <label>Item Description</label>
      <input type="text" class="form-control" [(ngModel)]="newItemDesc">
      <br>
      <button
        class="btn btn-primary"
        (click)="onAddItem(itemNameInput)">Add Item</button>
      <button
        class="btn btn-primary"
        (click)="onAddItemSpec()">Add Item Specifications</button>
    </div>
  </div>

Please note, I have commented the following line.

<!-- <input type="text" class="form-control" [(ngModel)]="newItemName"> -->

Replaced with the following line. Here instead of two-way data binding we are using template reference variable “#itemNameInput”. That is we have placed local reference on the input element “Item Name”.

<input 
    type="text" 
    class="form-control" 
    #itemNameInput>

Note, local reference can be placed on any HTML element and not only input element. You just have to use hash tag “#” followed by local reference variable name of your choice. For example, “#itemNameInput”. Also, note that this reference will hold reference to the whole HTML element with all its properties.

How to access template reference variables from component class ?

In the previous section you had learnt how to use or declare template reference variable in component’s template. Now, in this section let’s see how to access that template reference variable from component class.

First, let’s add argument the onAddItem() method in the template using template reference variable “itemnameInput” declared for the input element “Item Name” as shown below.

<button
     class="btn btn-primary"
     (click)="onAddItem(itemNameInput)">Add Item</button>

Therefore, your modified component’s template “create-item.component.html” should look like below with local references.

create-item.component.html

<div class="row">
    <div class="col-xs-12">
      <p>Create Items and Specifications!</p>
      <label>Item Name</label>
      <input 
          type="text" 
          class="form-control" 
          #itemNameInput>
      <label>Item Description</label>
      <input type="text" class="form-control" [(ngModel)]="newItemDesc">
      <br>
      <button
        class="btn btn-primary"
        (click)="onAddItem(itemNameInput)">Add Item</button>
      <button
        class="btn btn-primary"
        (click)="onAddItemSpec()">Add Item Specifications</button>
    </div>
  </div>

Now, let’s modify the create-item component class to access the template reference variable as shown below. Basically, I have modified onAddItem() method in component class to access template reference variable.

Therefore, I had added argument “itemNameInput” reference of type “HTMLInputElement” and then commented the following line //itemTitle: this.newItemName,  and added new line itemTitle: itemNameInput.value, .

  onAddItem(itemNameInput : HTMLInputElement) {
    this.itemAdded.emit({
        //itemTitle: this.newItemName, 
        itemTitle: itemNameInput.value, 
        itemDesc: this.newItemDesc
    });
  }

Finally, your component class should look like below.

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css']
})
export class CreateItemComponent implements OnInit {
  ---
  ---
  ---

  constructor() { }

  ngOnInit(): void {
  }

  onAddItem(itemNameInput : HTMLInputElement) {
    this.itemAdded.emit({
        //itemTitle: this.newItemName, 
        itemTitle: itemNameInput.value, 
        itemDesc: this.newItemDesc
    });
  }

  onAddItemSpec() {
    this.itemSpecAdded.emit({
      itemTitle: this.newItemName, 
      itemSpec: this.newItemSpec
    });
  }

}

That’s it. Now run the modified code it should work with local references. You had learnt how to declare template reference variables and access template reference variables from component class.

Hope it helped 🙂

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments