简体   繁体   English

Angular 12 ViewChild ElementRef

[英]Angular 12 ViewChild ElementRef

In previous versions of angular we could just define a viewchild with an element ref like so在以前的 angular 版本中,我们可以像这样定义一个带有元素 ref 的 viewchild

@ViewChild('fileInput') fileInput: ElementRef;

Now we have to initialize it in the constructor?现在我们必须在构造函数中初始化它? how do we do this for elementRef if there is no default nativeelement?如果没有默认的 nativeelement,我们如何为 elementRef 执行此操作? Element Ref takes in one argument https://angular.io/api/core/ElementRef Element Ref 接受一个参数https://angular.io/api/core/ElementRef

constructor() {
    this.fileInput = new ElementRef(?);
}

If you want to gain access to the ViewChild element, you can only do it after the AfterViewInit / AfterViewChecked lifecycle has been taken its course.如果您想访问ViewChild元素,则只能在AfterViewInit / AfterViewChecked生命周期结束后才能进行。 You don't need to manually create it, Angular will do that for you.您不需要手动创建它,Angular 会为您完成。 You can do see this occur in Angular Example 2 .您可以在Angular Example 2 中看到这种情况。

However, keep in mind, it is not possible to have access to it in the constructor, ngOnInit.但是,请记住,在构造函数 ngOnInit 中无法访问它。

If you want access to your own element component ElementRef you can do it has follows:如果你想访问你自己的元素组件 ElementRef 你可以这样做:

@Component(...)
export class CustomComponent {
  constructor(elementRef: ElementRef) {
    // Code here or store it via an attribute accessor
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM