How to get elementRef without constructor injection? - Angular

Viewed 573

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
   }
}
1 Answers

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.

Related