如何确保 ngAfterViewInit 在呈现某个 HTML 元素后运行?
How to make sure ngAfterViewInit runs after a certain HTML element is rendered?
在HTML中有一个<a>
重定向到另一个组件,然后滚动到某个锚点。
在目标组件中,我有以下代码
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
});
}
但是,我发现document.getElementById(fragment);
总是null
,因为这个元素是使用ngIf = booleanVariable
有条件显示的,当这个ngAfterViewInit
生命周期钩子运行时,这个booleanVariable
尚未计算。
我想知道如何确保 ngAfterViewInit
在计算 booleanVariable
之后运行并因此呈现此元素?
我尝试使用 setTime
但它看起来很老套...
提前致谢!
尝试改用 _elementRef:
this._elementRef.nativeElement.querySelector('#'+fragment)
您可以尝试等待下一个动画帧,让 html 元素有机会渲染。
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
window.requestAnimationFrame(_ => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
}
});
}
需要查看更多代码才能给出更可靠的答案。
感谢您的回答,但恐怕它们无法正常工作...
(也许我试错了。)
我设法使用
解决了这个问题
@ViewChild('elementId') set elementName(elementName: ElementRef) {
# code to scroll to a certain section of the page.
};
该方法将 运行 在 呈现此 ViewChild
之后。
在HTML中有一个<a>
重定向到另一个组件,然后滚动到某个锚点。
在目标组件中,我有以下代码
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
});
}
但是,我发现document.getElementById(fragment);
总是null
,因为这个元素是使用ngIf = booleanVariable
有条件显示的,当这个ngAfterViewInit
生命周期钩子运行时,这个booleanVariable
尚未计算。
我想知道如何确保 ngAfterViewInit
在计算 booleanVariable
之后运行并因此呈现此元素?
我尝试使用 setTime
但它看起来很老套...
提前致谢!
尝试改用 _elementRef:
this._elementRef.nativeElement.querySelector('#'+fragment)
您可以尝试等待下一个动画帧,让 html 元素有机会渲染。
ngAfterViewInit(): void {
this.route.fragment.subscribe(fragment => {
window.requestAnimationFrame(_ => {
const elmntLoc: HTMLElement = document.getElementById(fragment);
window.scroll({
top: elmntLoc.offsetTop,
behavior: "smooth"
});
}
});
}
需要查看更多代码才能给出更可靠的答案。
感谢您的回答,但恐怕它们无法正常工作... (也许我试错了。)
我设法使用
解决了这个问题 @ViewChild('elementId') set elementName(elementName: ElementRef) {
# code to scroll to a certain section of the page.
};
该方法将 运行 在 呈现此 ViewChild
之后。