2

I want to know if there is a way to get the ElementRef instance without the constructor injection in Angular?

Why I need it:

I have an abstract BaseComponent class that gets inherited in a lot of other Angular Component classes. I want to avoid injecting the ElementRef in all subclasses via super(elementRef) call and instead have it directly injected in the BaseComponent class -

export abstract class BaseComponent {
   private elementRef: ElementRef;
   constructor() {   
      // Do we have some option like below?
     //  this.elementRef = Injector.get(ElementRef) 
   }
}

@Component({
  selector: 'app-comp-one',
  templateUrl: './comp-one.component.html',
  styleUrls: ['./comp-one.component.css']
})
export class CompOne extends BaseComponent {
    constructor() {  // constructor(elementRef: ElementRef)
      super();            // super(elementRef);  
     // here I can pass elementRef in super constructor call
     // but that's what I don't want to do
   }
}
Akash
  • 4,412
  • 4
  • 30
  • 48

2 Answers2

0

Angular has the inject(...) function that can inject tokens during an injection context (such as during the construction of a component, like in your example). The full specs can be found here: https://angular.io/api/core/inject

For ElementRef, you can inject it like this:

private readonly elementRef: ElementRef = inject(ElementRef);

If you want to specify the generic type on ElementRef, you can inject it like this:

private readonly elementRef: ElementRef<HTMLElement> = inject<ElementRef<HTMLElement>>(ElementRef);
Jake Tyler
  • 180
  • 2
  • 9
-1

I didn't test it but i found your question interesting, so i made a few research and i found this which resolve the exact problem you want to solve.

Gauthier T.
  • 556
  • 1
  • 4
  • 16
  • 1
    I don't think that solution will work in case of `ElementRef`. `ElementRef` is tied to specific Component/Directive. You can't use module level injector to get that instance. You should be taking it from ElementInjector. – yurzui Aug 26 '20 at 02:13