0 votes
in Angular by
references template angular

1 Answer

0 votes
by
This article is all about Template Reference variable or Local Reference variable, whatever you can say. I think you can get some idea with the name itself “Template Reference” which says we are looking forward to putting a reference to any template. Let me explain this with an example.

Let’s say we have some basic DOM elements in our template view. It can be anything like

<div>

<h2>I am h2</h2>

<p>I am Paragraph</p>

</div>

And we want to access the content of h2 tag element inside our template but not in the component class. After accessing it, we also want to display below the parent div. How can we do that? The answer is “Template Reference variable”. Yes, by placing a template or local reference variable over that element.

Angular provides us, a way of capturing a reference to any specific dom element, component or directive in order to use it somewhere in our template itself.

We just have to mark that specific element with a name followed by hash(#) symbol. Once the element gets marked, it will be treated as a local reference variable for that template and can be used to access its properties inside the template view only. You can not access it inside the component class or typescript logic codes.

<div>

<h2 #h2Elm>I am h2</h2>

<p>I am Paragraph</p>

</div>

<hr>

{{h2Elm.textContent}}

insert

we can do the same here for component and directives too

<hello name="Template Ref Variable" #helloRef></hello>

{{helloRef.name}} //   Template Ref Variable

Note: The identifier name used for the template reference variable should be unique and should not conflict with any other template reference variable.

Well! I told you that you cannot access that template reference variable inside the component class or typescript logic but still, you can use that variable by passing it through a method which will be called by the event listener.

<div>

<label for="Name">Name</label>

<input type="text" #nameInput>

<button (click)="onSaveName(nameInput)">Save Name</button>

</div>

Passing that local variable with omitting # symbol.

import {

  Component,

} from '@angular/core';

@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent {

  constructor() {}

  onSaveName(name: HTMLInputElement) {

    console.log(( < HTMLInputElement > name).value);

  }

}

Here, if you observe, we are expecting a name parameter which will be of type HTMLInputElement and also inside the body of the method, we have wrapped the name variable with the same type. It is because we are accessing the instance of the element which is <input> type.

Related questions

0 votes
0 votes
asked Aug 11, 2023 in Angular by DavidAnderson
0 votes
asked Aug 11, 2023 in Angular by DavidAnderson
...