I'm trying to get a reference to the DOM element for a ponent in an Angular 2 template using a template reference variable. This works on normal html tags but has a different behaviour on ponents. e.g.
<!--var1 refers to the DOM node -->
<div #var1></div>
<!--var2 refers to the ponent but I want to get the DOM node -->
<my-p #var2></my-p>
Is there any way force the template reference variable to refer to the DOM node even if it is on a ponent? And if so is it covered in the docs anywhere? The only docs I can find on this are here .html#!#ref-vars and they don't go into much detail on how the variables are resolved.
I'm trying to get a reference to the DOM element for a ponent in an Angular 2 template using a template reference variable. This works on normal html tags but has a different behaviour on ponents. e.g.
<!--var1 refers to the DOM node -->
<div #var1></div>
<!--var2 refers to the ponent but I want to get the DOM node -->
<my-p #var2></my-p>
Is there any way force the template reference variable to refer to the DOM node even if it is on a ponent? 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.
Share Improve this question asked Feb 12, 2017 at 2:05 robrob 18.5k13 gold badges71 silver badges95 bronze badges2 Answers
Reset to default 10It depends on how you are going to use this reference.
1) There is no straight way to get ponent 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-p [(element)]="var2"></my-p>
<p>{{var2}}</p>
<!--or-->
<my-p element #var2="element"></my-p>
<p>{{var2.element}}</p>
2) You can get this reference in ponent 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);
}
}