gpt4 book ai didi

Angular2 选择带有 ngIf 的元素

转载 作者:行者123 更新时间:2023-12-02 17:15:07 24 4
gpt4 key购买 nike

这是我的 html :

<div id="foo" (mouseover)="blah()" *ngIf="isDisplayed"></div>

还有我的js:

isDisplayed: boolean = false
blah() {
this.isDisplayed = true
console.log(document.getElementById('foo'))
}

但是,我的 console.log 确实打印了 null。如果我在 console.log 周围添加一个 setTimeout,它可以工作,但是这很糟糕,并且当多个事件同时发生时会变得一团糟。我的意思是,我确实知道 getElementById 是在模板的 ngIf 更新之前运行的。我如何确保在运行 console.log 时模板已更新?

最佳答案

显式调用更改检测,然后 Angular 将立即更新 DOM。

constructor(private cdRef:ChangeDetectorRef) {}

isDisplayed: boolean = false
blah() {
this.isDisplayed = true;
this.cdRef.detectChanges();
console.log(document.getElementById('foo'));
}

关于Angular2 选择带有 ngIf 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40862534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com