在角的早期版本中,我们只需定义一个viewchild,其元素引用如下
@ViewChild('fileInput') fileInput: ElementRef;现在我们必须在构造函数中初始化它?如果没有默认的本地元素,我们如何为elementRef做到这一点?元素引用一个参数https://angular.io/api/core/ElementRef
constructor() {
this.fileInput = new ElementRef(?);
}发布于 2021-07-28 14:02:44
如果您想获得对AfterViewInit/AfterViewChecked ViewChild元素的访问权,则只能在生命周期完成之后才能这样做。您不需要手动创建它,角将为您做到这一点。您可以在角例2中看到这种情况。
但是,请记住,在构造函数ngOnInit中不可能访问它。
如果您希望访问您自己的元素组件ElementRef,您可以这样做:
@Component(...)
export class CustomComponent {
constructor(elementRef: ElementRef) {
// Code here or store it via an attribute accessor
}
}发布于 2021-09-13 13:31:52
而不是:
@ViewChild('fileInput') fileInput: ElementRef;使用:
@ViewChild('fileInput') fileInput!: ElementRef;它应该没有任何问题。
https://stackoverflow.com/questions/68561609
复制相似问题