Skip to content Skip to sidebar Skip to footer

Access DOM Element With Template Reference Variables On Component

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 be

Solution 1:

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}).


Solution 2:

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);
    }
}

Post a Comment for "Access DOM Element With Template Reference Variables On Component"