![](/img/trans.png)
[英]How to use js dom manipulation on elements accessed by using ViewChild
[英]How to use ViewChild correctly
這個 Angular 應用只包含app-root
組件和一個<div>
和一個<button>
。
單擊按鈕時, onClick()
函數會記錄以控制台div_a
對象:
console.log("...onClick() div_a:", this.div_a);
使用以下語句定義div_a
:
@ViewChild('div_a', { static: false }) div_a: Component;
問題:為什么ngOnInit
和constructor
函數都記錄div_a
未定義? 如何解決這些函數無法使用div_a
對象的問題?
下面是Stackblitz項目的鏈接(請注意,鏈接到這個stackblitz
項目的GitHub分支需要從master
切換到qViewChild
分支)。
https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html
根據文檔, ViewChild
和ViewChildren
查詢在AfterViewInit
之前AfterViewInit
,因此您需要在那里訪問它們。 除非您在模板中標記它,否則僅訪問div_a
將不起作用。
其中,您可以訪問的孩子包括:
<my-component #cmp></my-component>
)所以你需要這樣的東西:
<p #myPara>
Start editing to see some magic happen :)
</p>
import { Component, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('myPara', {static: false}) paragraph;
ngAfterViewInit() {
console.log(this.paragraph) // results in -> ElementRef {nativeElement: p}
}
}
Cuando 使用@ViewChild NO utilices ngOnInit o 構造函數porque aún no se carga。 使用 ngAfterViewInit() 函數
翻譯:
使用 @ViewChild 時不要使用 ngOnInit 或構造函數,因為它尚未加載。 使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.