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.

2
  • 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. Commented Apr 6, 2020 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. stackoverflow.com/questions/42183472 Commented Apr 6, 2020 at 17:04

1 Answer 1

5

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) { }     
}
Sign up to request clarification or add additional context in comments.

4 Comments

OMG, this is so ugly, but definitely working. I like! I will keep the answer opened a few days to see if there is any other ways to do it.
Ok no problem, feel free to share if you find any other solution!
This is indeed very ugly, surely there must be a better way?
I think this is actually a rather elegant solution (naming conventions aside)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.