Tim*_*imo 2 javascript scroll typescript angular
我想在我的视图第一次初始化后滚动到一个 div。到目前为止我的问题是 AfterViewInit 导致了一个问题,因为它没有完全渲染。(从服务器获取数据,然后渲染该数据..)
到目前为止的代码:
scrollTo(): void {
if (!this.jumpedToMessage && this.jumpMessage != "0") {
const element = document.getElementById(this.jumpMessage);
// @ts-ignore
element.scrollIntoView({behavior: 'auto', block: 'center', inline: 'nearest'});
this.jumpedToMessage = true
}
}
Run Code Online (Sandbox Code Playgroud)
控制台中的错误代码:
my-component.ts:58 错误 TypeError: 无法在 Object.next (my-component.component) 的 my-component.scrollTo (my-component.component.ts:76:15) 处读取 null 属性(读取“scrollIntoView”) .ts:65:18) 在 ConsumerObserver.next (Subscriber.js:91:33) 在 SafeSubscriber._next (Subscriber.js:60:26) 在 SafeSubscriber.next (Subscriber.js:31:18) 在 map.js :7:24 在 OperatorSubscriber._next (OperatorSubscriber.js:13:21) 在 OperatorSubscriber.next (Subscriber.js:31:18) 在 filter.js:6:128 在 OperatorSubscriber._next (OperatorSubscriber.js:13:21) )
有什么想法如何解决这个问题吗?
重要提示: 首次渲染后仅初始化一次
也许您可以尝试使用不同的方法来实现您的目标,@ViewChild无论如何,这都会更像 Angular。
在你的HTML中:
<p #scrollElement>Scroll here</p>
Run Code Online (Sandbox Code Playgroud)
然后在你的TS 文件中:
@ViewChild("scrollElement")
scrollEl: ElementRef;
ngAfterViewInit() {
this.scrollEl.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2499 次 |
| 最近记录: |