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 #
Nonetheless, if we use a structural directive like * ngIf or *
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
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
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
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.