[英]How to get elementRef without constructor injection? - Angular
I want to know if there is a way to get the ElementRef
instance without the constructor injection in Angular
?我想知道是否有办法在
Angular
没有构造函数注入的情况下获取ElementRef
实例?
Why I need it:为什么我需要它:
I have an abstract BaseComponent class that gets inherited in a lot of other Angular Component classes.我有一个抽象的 BaseComponent 类,它在许多其他 Angular Component 类中被继承。 I want to avoid injecting the
ElementRef
in all subclasses via super(elementRef)
call and instead have it directly injected in the BaseComponent class -我想避免通过
super(elementRef)
调用在所有子类中注入ElementRef
,而是直接将其注入 BaseComponent 类中 -
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
}
}
我没有测试它,但我发现你的问题很有趣,所以我做了一些研究,我发现这解决了你想要解决的确切问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.