首页 > 解决方案 > 如何等到 ngIf 在 DOM 中插入内容?

问题描述

Stackblitz 示例

    import { Component, Input,ViewChild,ElementRef } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>

  <button (click)='setFoo()'>Trigger NG IF</button>

  <div *ngIf="myFooBoolean" #fooDiv>
  myFooBoolean was set to true
  </div>
`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  @Input() name: string;
  myFooBoolean: boolean;
  @ViewChild('fooDiv', {static: false}) fooDiv: ElementRef;

  setFoo() {
    this.myFooBoolean = true;
    const el: HTMLDivElement = this.fooDiv.nativeElement;
    console.log(el);
  }
}

如果您单击该按钮,您将在控制台中看到一个错误,因为您正在尝试访问一个正在插入 DOM 的元素,Ngif我可以通过使用来克服此错误setTimeout()

但是还有其他更好的方法来解决它吗?

标签: angular

解决方案


我能想到的有两种选择:

1:实现ngAfterContentChecked() 等到在dom中的每次更改检测(当您的元素显示/隐藏,以及很多其他事情时)被angular调用。根据您的用例,这可能不是很有用。

2:将 a 注入ChangeDetectorRef到您的组件中,并在设置好myFooBooleanrunChangeDetectorRef.detectChanges()之后,之后的行应该能够正常访问您的 viewchild。


推荐阅读