首页 > 解决方案 > Angular v8 - @ViewChild 静态真或假

问题描述

Angular v8 刚刚发布。尽管它主要是向后兼容的,但还是有一些重大变化。

根据 Angular 的变更日志,一个核心变化是(我引用):

“在 Angular 版本 8 中,要求所有 @ViewChild 和 @ContentChild 查询都有一个‘静态’标志,指定查询是‘静态’还是‘动态’。”

它还指出,在大多数情况下,只需设置即可{ static: false }

@ViewChild('selectorName', { static: false }) varName: any;

我的问题是我什么时候应该将此属性(静态)设置为true?它将如何影响我的申请???

标签: angularangular8viewchild

解决方案


{ static: true }当您想要访问ViewChildin时使用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


推荐阅读