簡體   English   中英

如何正確使用 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;

問題:為什么ngOnInitconstructor函數都記錄div_a未定義? 如何解決這些函數無法使用div_a對象的問題?

下面是Stackblitz項目的鏈接(請注意,鏈接到這個stackblitz項目的GitHub分支需要從master切換到qViewChild分支)。

https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html

在此處輸入圖片說明

根據文檔ViewChildViewChildren查詢在AfterViewInit之前AfterViewInit ,因此您需要在那里訪問它們。 除非您在模板中標記它,否則僅訪問div_a將不起作用。

其中,您可以訪問的孩子包括:

  • 任何帶有 @Component 或 @Directive 裝飾器的類
  • 作為字符串的模板引用變量(例如使用 @ViewChild('cmp') 查詢<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM