[英]Looking for an Angular 7 version of Vue.js "nextTick"
I'm developing a page in Angular 7, where i want to do something (scroll to section) after i'm sure the page has re rendered.我正在 Angular 7 中开发一个页面,在确定页面已重新呈现后,我想在其中做一些事情(滚动到部分)。 The section i want to scroll to is initially hidden with an ngif and when the section is shown and completely rendered in the DOM, then i want to scroll to it.
我想要滚动到的部分最初是用 ngif 隐藏的,当该部分显示并完全呈现在 DOM 中时,我想滚动到它。 I've used Vue.js before and their callback function nextTick, which has been working but i can't find a similar solution in angular. I'd rather not use a setTimeout because if set to 0 the DOM is not always ready and re rendered and setting it higher makes it delayed.
我之前使用过 Vue.js 和他们的回调 function nextTick,它一直在工作,但我在 angular 中找不到类似的解决方案。我宁愿不使用 setTimeout,因为如果设置为 0,DOM 并不总是准备好并重新渲染并将其设置得更高会使它延迟。
You could put inside your *ngIf a component and use the AfterViewInit lifecycle hook which will call a parent function after he rendered properly. 您可以将* ngIf组件放入其中,并使用AfterViewInit生命周期钩子,该钩子将在正确渲染后调用父函数。
https://angular.io/api/core/AfterViewInit https://angular.io/api/core/AfterViewInit
Why not try requestAnimationFrame
?为什么不试试
requestAnimationFrame
呢? It worked for me.它对我有用。 You don't need to set a time while DOM is always rerendered and runs with no delay.
您无需设置时间,而 DOM 始终会重新渲染并无延迟地运行。
well the angular alternate would be setting settimeout to 0 in your code where the if flag is changed and then immediately calling ChangeDetectorRef.detectchanges() after it so it shall force to detect the change in the immediate next cycle, something in your component like好吧,angular 替代方案将在您的代码中将 settimeout 设置为 0,其中 if 标志已更改,然后在它之后立即调用 ChangeDetectorRef.detectchanges() 因此它将强制检测紧接下一个周期的变化,您的组件中的某些内容如
...
sectionRendered = false;
constructor(private cdf: ChangeDetectorRef){
}
function renderSection(){
this.sectionRendered = true;
setTimeout(() => {
// here you can access the relevant component
this.scrollSection();
}, 0);
this.cdf.detectChanges();
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.