Template Reference Variables in Angular

Posted By : Manisha Kirodiwal | 30-Aug-2018

Goal:
How to get a reference of a directive in the template

Implementation:

A template reference variable is often a reference to a DOM element in a template. It may also be a reference to an angle component or a directive or web component. This means that you can easily access the variable anywhere in the template. In other words, the template reference variable is a way to get a reference to a particular object, component, or directive, so it can be used somewhere else in the same template.


They are declared as this # myReference or this # myReference = "switch". Once declared, they can be used anywhere in the template.
Nonetheless, if we use a structural directive like * ngIf or *
ngFor or a <ng template> , it always creates a new template economizer so any template reference variables specified will not be available for use outside.

Template reference variables solving orders are:
1. A directive or component specifically referred to its exportAs property like this: # myToggle = "switch".

2. The component attached to the element, if it is present.<toggle-on #toggleOn></toggle-on>
3.  By using <div #someDiv></div> you can create a html element reference, if no component is present.


1. Directive with exportAs:

By using exportAs property in metadata of a directive, it allows this directive to be specifically targeted by a template reference variable.
So that we can use directive reference in the specified template.

 

// toggle.directive.ts
@Directive({
  selector: '[toggle]',
  exportAs: 'toggle',
})
export class ToggleDirective { ... }
// app.component.html
 
// myTemplateRefVar is the ToggleDirective


2. Component:
There can only be one component per. HTML element. If there is a component attached to the item, solve a clean template reference variable for that component.

// app.component.html

// toggleOn is the ToggleOnComponent

3. HTML Element:
If there is no component attached to the item, the template reference variable will fall back to the element itself.

// app.component.html
 
// someDiv is an HTMLDivElement


Note:
In this example, I print the class name of the template reference variables using constructor.name to make it clear for each variable.
What the above syntax does is quite simple: It creates a reference to the input element that can be used later in my template. Note that the scope of this variable is the entire HTML template where the reference is defined.

 

About Author

Author Image
Manisha Kirodiwal

Manisha is a Web Application developer and she is good in working with Angular, TypeScript , JavaScript and Jquery. In free time she loves to dance and cooking.

Request for Proposal

Name is required

Comment is required

Sending message..