[英]How to make sure ngAfterViewInit runs after a certain HTML element is rendered?
In HTML, there is a <a>
that redirects to another component, and after that scrolls to a certain anchor.在 HTML 中,有一个
<a>
重定向到另一个组件,然后滚动到某个锚点。
In the target component, I have the following code在目标组件中,我有以下代码
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
});
}
However, I found that document.getElementById(fragment);
但是,我发现
document.getElementById(fragment);
is always null
, because this element is displayed conditionally using ngIf = booleanVariable
, and when this ngAfterViewInit
life cycle hook runs, this booleanVariable
is not calculated yet.始终为
null
,因为此元素使用ngIf = booleanVariable
有条件地显示,并且当此ngAfterViewInit
生命周期挂钩运行时,此booleanVariable
尚未计算。
I am wondering how to make sure ngAfterViewInit
runs after booleanVariable
is calculated and therefore this element is rendered?我想知道如何确保
ngAfterViewInit
在计算booleanVariable
并因此呈现该元素之后运行?
I tried to use setTime
but it seems hacky...我尝试使用
setTime
但它似乎很hacky......
Thanks in advance!提前致谢!
Try using _elementRef instead:尝试使用 _elementRef 代替:
this._elementRef.nativeElement.querySelector('#'+fragment)
You could try waiting for the next animation frame to give a chance for the html element to render.您可以尝试等待下一个 animation 帧给 html 元素渲染的机会。
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
window.requestAnimationFrame(_ => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
}
});
}
Need to see more of your code to give a more robust answer.需要查看更多代码才能给出更可靠的答案。
Thanks for the answers but they don't work properly I am afraid... (Perhaps I tried them in a wrong way.)感谢您的回答,但恐怕它们无法正常工作......(也许我以错误的方式尝试了它们。)
I managed to solve this problem using我设法解决了这个问题
@ViewChild('elementId') set elementName(elementName: ElementRef) {
# code to scroll to a certain section of the page.
};
The method will run after this ViewChild
is rendered.该方法将在此
ViewChild
呈现后运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.