![](/img/trans.png)
[英]@ViewChild('tTaskTeam', { read: MatAutocompleteTrigger }) is not working after upgrading to V8
[英]Angular v8 - @ViewChild static true or false
Angular v8 剛剛發布。 雖然它主要是向后兼容的,但還是有一些突破性的變化。
根據 Angular 的Changelog,一個核心變化是(我引用):
它還指出,在大多數情況下,只需設置{ static: false }
。
@ViewChild('selectorName', { static: false }) varName: any;
我的問題是我什么時候應該將此屬性(靜態)設置為true
? 以及它將如何影響我的申請???
當您想訪問ViewChild
中的ngOnInit
時,請使用{ static: true }
。
使用{ static: false }
只能在ngAfterViewInit
訪問。 當您的模板中有結構指令( *ngIf
等)時,這也是您想要執行的操作。
在大多數情況下{ static: false }
會起作用。
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'example', templateUrl: './example.component.html', styleUrls: ['./example.component.scss'] }) export class ExampleComponent implements OnInit, AfterViewInit { @ViewChild('elementA', { static: true }) elementStatic: ElementRef<HTMLElement>; @ViewChild('elementB', { static: false }) elementDynamic: ElementRef<HTMLElement>; public ngOnInit(): void { this.elementStatic.nativeElement; // Ok this.elementDynamic.nativeElement; // ERROR TypeError: Cannot read property 'nativeElement' of undefined } public ngAfterViewInit(): void { this.elementStatic.nativeElement; // Ok this.elementDynamic.nativeElement; // Ok } }
<div #elementA>A</div> <div #elementB>B</div>
更新:從 Angular v9.x 開始, static 的默認值為false 。
閱讀更多信息: https : //angular.io/api/core/ViewChild#viewchild
從文檔:
如何選擇要使用的靜態標志值:true 還是 false?
在官方 API 文檔中,我們一直建議在 ngAfterViewInit 中檢索查詢結果以進行視圖查詢,在 ngAfterContentInit 中檢索查詢結果以進行內容查詢。 這是因為當這些生命周期鈎子運行時,相關節點的變更檢測已經完成,我們可以保證我們已經收集了所有可能的查詢結果。
出於同樣的原因,大多數應用程序都希望使用 {static: false}。 此設置將確保查詢會找到依賴於綁定解析的查詢匹配(例如 *ngIfs 或 *ngFors 內的結果)。
在極少數情況下可能需要 {static: true} 標志(請參閱此處的答案)。
何時使用{static:true}
https://angular.io/guide/static-query-migration#should-i-use-static-true
這用非常簡單的術語來解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.