![](/img/trans.png)
[英]Angular 12: ViewChild not working for ElementRef inside modals
[英]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.