angular - 如何等到 ngIf 在 DOM 中插入内容?
问题描述
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()
但是还有其他更好的方法来解决它吗?
解决方案
我能想到的有两种选择:
1:实现ngAfterContentChecked()
等到在dom中的每次更改检测(当您的元素显示/隐藏,以及很多其他事情时)被angular调用。根据您的用例,这可能不是很有用。
2:将 a 注入ChangeDetectorRef
到您的组件中,并在设置好myFooBoolean
runChangeDetectorRef.detectChanges()
之后,之后的行应该能够正常访问您的 viewchild。
推荐阅读
- python-3.x - 将索引转换为 pandas 列
- git - 用于分支的 Visual Studio Code Git 扩展
- c# - 覆盖语言后更改对话框的语言?
- graphql - [vue-apollo]:查询getTeam发生错误
- java - javamail isSSL false 即使我在发送邮件时将 tls 设置为 True
- unity3d - 在android中保存json文件
- r - R中字符变量加权频率的时间序列图
- node.js - 运行 quorra 时出错:无法识别 quorra
- charts - Power BI 自定义模式窗口
- python - 在 Python Jinja 模板中的 for 循环内应用 if 语句