![](/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.