5

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.

jsgoupil
  • 3,788
  • 3
  • 38
  • 53
  • Now it looks like I'm talking to myself, @trevor-karjanis had asked a question in comments here but deleted it. The connected question to this one would be similar but the answer is not as good as quality goes. – jsgoupil Apr 06 '20 at 15:41
  • 1
    Sorry, I had flagged this as a duplicate, and it automatically commented. I'm not sure why that comment was removed. I intended to post a new answer on the duplicate. https://stackoverflow.com/questions/42183472 – Trevor Karjanis Apr 06 '20 at 17:04

1 Answers1

4

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) { }     
}
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60