繁体   English   中英

Angular 12 ViewChild ElementRef

[英]Angular 12 ViewChild ElementRef

在以前的 angular 版本中,我们可以像这样定义一个带有元素 ref 的 viewchild

@ViewChild('fileInput') fileInput: ElementRef;

现在我们必须在构造函数中初始化它? 如果没有默认的 nativeelement,我们如何为 elementRef 执行此操作? Element Ref 接受一个参数https://angular.io/api/core/ElementRef

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

如果您想访问ViewChild元素,则只能在AfterViewInit / AfterViewChecked生命周期结束后才能进行。 您不需要手动创建它,Angular 会为您完成。 您可以在Angular Example 2 中看到这种情况。

但是,请记住,在构造函数 ngOnInit 中无法访问它。

如果你想访问你自己的元素组件 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