angularangular-template-variable

Get the ElementRef from the Template reference variable in Angular


In the following code

<input #myRef1 />
<input #myRef2 my-custom-attribute />

The #myRef1 will be an ElementRef, and #myRef2 will be MyCustomAttributeComponent directive. Basically, it implicitly finds the first component and associates it to the template reference variable. I can force which directive/component I want thanks to exportAs, but here, I actually want the ElementRef in both cases.

Is there something to force #myRef2 to be an ElementRef WITHOUT the TypeScript @ViewChild(..., { read: ElementRef }). I need to access myRef2 as an ElementRef in my template.


Solution

  • Inject ElementRef Service in directive, then access injected service reference in template like this

    component.html

    <input #ref="custom" type="text" appCustom>
    {{ref.template}}
    

    directive.ts

    import { Directive, ElementRef } from '@angular/core';
    @Directive({
        selector: '[appCustom]',
        exportAs: 'custom'
    })
    export class CustomDirective {     
             constructor(public template:ElementRef) { }     
    }