I'm trying to get a reference to the DOM element for a component in an Angular 2 template using a template reference variable. This works on normal html tags but has a different behaviour on components. e.g.
<!--var1 refers to the DOM node -->
<div #var1></div>
<!--var2 refers to the component but I want to get the DOM node -->
<my-comp #var2></my-comp>
Is there any way force the template reference variable to refer to the DOM node even if it is on a component? And if so is it covered in the docs anywhere? The only docs I can find on this are here https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars and they don't go into much detail on how the variables are resolved.
It depends on how you are going to use this reference.
1) There is no straight way to get component DOM reference within template:
import {Directive, Input, ElementRef, EventEmitter, Output, OnInit} from '@angular/core';
@Directive({selector: '[element]', exportAs: 'element'})
export class NgElementRef implements OnInit
{
@Output()
public elementChange:EventEmitter<any> = new EventEmitter<any>();
public elementRef:ElementRef;
constructor(elementRef:ElementRef)
{
this.elementRef = elementRef;
this.elementChange.next(undefined);
}
@Input()
public get element():any
{
return this.elementRef.nativeElement;
}
public set element(value:any)
{
}
ngOnInit():void
{
this.elementChange.next(this.elementRef.nativeElement);
}
}
Usage:
<my-comp [(element)]="var2"></my-comp>
<p>{{var2}}</p>
<!--or-->
<my-comp element #var2="element"></my-comp>
<p>{{var2.element}}</p>
2) You can get this reference in component that owns template with @ViewChild('var2', {read: ElementRef})
.
As of Angular 8, the following provides access to the ElementRef and native element.
/**
* Export the ElementRef of the selected element for use with template references.
*
* @example
* <button mat-button #button="appElementRef" appElementRef></button>
*/
@Directive({
selector: '[appElementRef]',
exportAs: 'appElementRef'
})
export class ElementRefDirective<T> extends ElementRef<T> {
constructor(elementRef: ElementRef<T>) {
super(elementRef.nativeElement);
}
}