angular - Angular v8 - @ViewChild 静态真或假
问题描述
Angular v8 刚刚发布。尽管它主要是向后兼容的,但还是有一些重大变化。
根据 Angular 的变更日志,一个核心变化是(我引用):
“在 Angular 版本 8 中,要求所有 @ViewChild 和 @ContentChild 查询都有一个‘静态’标志,指定查询是‘静态’还是‘动态’。”
它还指出,在大多数情况下,只需设置即可{ static: false }
。
@ViewChild('selectorName', { static: false }) varName: any;
我的问题是我什么时候应该将此属性(静态)设置为true
?它将如何影响我的申请???
解决方案
{ static: true }
当您想要访问ViewChild
in时使用ngOnInit
。
{ 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 开始,静态的默认值为false。
阅读更多:https ://angular.io/api/core/ViewChild#viewchild
推荐阅读
- python - 在python中带有“不再显示此消息”的QMessageBox
- html - 填写 HTML 登录表单并下载数据
- amazon-web-services - Spark Scala EMR 作业无法从 S3 下载文件
- r - 更改优势比图上 y 轴标签的顺序
- angular - 执行完所有for循环后执行代码
- docker - 如何使用状态管理设置 dapr 和 docker compose
- r - 更新反应性闪亮数据
- micronaut - 使用 Maven 和 Micronaut 框架构建原生镜像
- asp.net-core - 就绪探测和健康检查有什么好处?
- firefox - Firefox 禁用自定义工具栏选项或密码保护它