Angular 12 ViewChild ElementRef

4
在之前版本的Angular中,我们可以使用元素引用(element ref)来定义一个ViewChild,如下所示。
@ViewChild('fileInput') fileInput: ElementRef;

现在我们必须在构造函数中初始化它吗?如果没有默认的native element,我们该如何处理elementRef? Element Ref接收一个参数。 https://angular.io/api/core/ElementRef
constructor() {
    this.fileInput = new ElementRef(?);
}

请查看文档:https://angular.io/api/core/ViewChild 您不需要实例化任何东西。Angular会为您完成这个过程,并将该值分配给该属性。您必须确保只在适当的生命周期钩子期间(或之后)尝试访问该属性。 - peinearydevelopment
2
你需要在ViewChild中使用!,以指示Angular严格模式不要初始化变量:@ViewChild('fileInput') fileInput ! : ElementRef; 更多关于严格模式的信息请参见https://indepth.dev/posts/1402/bulletproof-angular - Eliseo
2个回答

1
如果您想访问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
  }
}

0

改为:

@ViewChild('fileInput') fileInput: ElementRef;

使用:

@ViewChild('fileInput') fileInput!: ElementRef;

它应该可以毫无问题地工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接