iFour Team - July 06, 2021
Angular’s template reference variables give a useful API across which you can interconnect with DOM elements and child components directly in your angular code. In the sections that follow, you will learn what template reference variables are and how you can use them in your angular components and services to gain a low level. Physical authority over the template elements that you are referencing.
Angular ElementRef is a cover throughout a native element inside of a view.
It is simply a class that wraps native DOM elements in the browser and allows you to work with DOM by providing a native element object which exposes all the methods and properties of the native elements.
To get started using template reference variables, simply create a new angular component to use an existing one.
To create a template reference variable, locate the HTML element that you want to reference and then that is like #myVarTitle.
In the below code, a template reference variable is created that references the
with id test-div.
[app.component.html]
Before we explore DOM abstractions, let’s understand how we access abstractions inside a component/directive class.
Angular provides a mechanism called DOM queries.
It comes in the form of @ViewChild decorators.
Finding successfully created a reference to an HTML element within the template.
You can now take this element inside of the appropriate angular component typescript file.
Within your angular component, use the Viewchild decorator that angular supplies applicable to bind to the previously created template reference variable.
If you observe its class structure, you’ll see that it only holds the native element it’s associated with.
For HTML elements, use the Viewchild decorator to create a new ElementRef as indicated below:
@ViewChild('myTestDiv') myTestDiv: ElementRef;
[app.component.ts]
This ElementRef gives your component direct access to the underlying HTML element when you use its native Element field like this:
const divEl: HTMLDivElement = this.myTestDiv.nativeElement;
[app.component.ts]
The Template reference variable will remain null or undefined until the view portion of the component has finished initiating.
Make sure you only attempt to use these variables within the ngAfterViewInit lifecycle hook or after this hook completes.
Native Element: The basic native element or null if direct access to native elements is not kept up. (E.g. when the website runs in a web worker)
Element Ref can be returned for any DOM element using the ViewChild decorator.
But since all components are hosted inside a custom DOM element and all directives are applied to DOM elements, component and all directive classes can obtain an instance of Element Ref associated with their host element through Dependency injection.
Accessing underlying HTML elements in your angular templates is substantial.
But what if you want to take child components within your template?
This is too easy to apply template reference variables.
Using the same syntax above, you can create a template reference variable on a child component such as this:
With your child component referenced, you can gain access to it in your angular component like this:
@ViewChild('myTestComp') myTestComp: TestComponent;
With your child component successfully captured, you can take it like this:
ngAfterViewInit(): void { // We can access the TestComponent now that this portion of the view tree has been initiated. this.myTestComp.saveTheWorld(); }
Creating an angular directive allows us to reuse this directive in different components.
Now we’ll demonstrate an example of how to used element Ref in our custom directive.
For custom directives, the directive needs to access its host element for manipulation.
The element Ref which we will inject in the directive construct will give direct access to the host component or element in DOM for manipulation.
Now let’s generate a directive called hoverer in our project and run the following command to create our custom directive.
ng generate directive directives/hoverer
Now let's edit our custom directive hover and add the following code.
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appHoverer]', host: { '(mouseenter)': 'onMouseHover()', '(mouseleave)': 'onMouseLeave()' } }) export class HovererDirective { constructor(private element: ElementRef) { } onMouseHover() { this.element.nativeElement.style.color = 'pink'; } onMouseLeave() { this.element.nativeElement.style.color = 'yellow'; } }
[app.component.ts]
In the example of the custom directive, we have two functions:
1. on Mouse Hover: This method is called when the mouse hovers on our paragraph element. Based on hover we change the paragraph font color to pink and you can change any style based on your requirement.
2. on Mouse Leave: This method is called when the mouse moves away from our paragraph element and based on the event we apply yellow to our font.
And another is, in our app.component.HTML file add the below code and we have applied our custom directive selector name in our paragraph.
This is an element to which we want to apply a style using element Ref.
Hover here to mouse to change font color.
The best way to prevent XSS attacks is to prevent untrusted data from getting injected into the DOM tree.
Angular has DOMSanitizer class, which helps to check Cross-site Scripting Security bugs(XSS) by sanitizing values to be safe to use in the different DOM elements.
Angular DOMSanitizer class has many methods that we can use and we used hardly one method for our example.
So we have used and applied DOMSanitizer class on our previous element Ref on angular directives.
import { Directive, ElementRef } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Directive({ selector: '[appHoverer]', host: { '(mouseenter)': 'onMouseHover()', '(mouseleave)': 'onMouseLeave()' } }) export class HovererDirective { constructor(private element: ElementRef, private sanitizer: DomSanitizer) { } onMouseHover() { this.sanitizer.bypassSecurityTrustHtml(this.element.nativeElement.style.color = 'pink'); } onMouseLeave() { this.sanitizer.bypassSecurityTrustHtml(this.element.nativeElement.style.color = 'yellow'); } }
When to used bypassSecurityTrustHtml method of DOMSanitizer.
Bypass security and trust the given value to be safe HTML.
Only use this when the bound HTML intact, so in most situations, this method should not be used.
In this blog, you learned what template reference variables are in the Angular framework and how to use them to gain typed references to both HTML elements located on the DOM and child components.
January 23, 2023
September 21, 2021
September 20, 2021
July 23, 2021
July 06, 2021
Technology that meets your business requirements
Planning a cutting-edge technology software solution? Our team can assist you to handle any technology challenge. Our custom software development team has great expertise in most emerging technologies. At iFour, our major concern is towards driving acute flexibility in your custom software development. For the entire software development life-cycle, we implement any type of workflow requested by the client. We also provide a set of distinct flexible engagement models for our clients to select the most optimal solution for their business. We assist our customers to get the required edge that is needed to take their present business to next level by delivering various out-reaching technologies.
Get advanced technology that will help you find the
right answers for your every business need.
Get in touch
Drop us a line! We are here to answer your questions 24/7.