Angular 5 无法读取 属性 'scrollIntoView' 的 null
Angular 5 Cannot read property 'scrollIntoView' of null
我想在页面加载时将页面滚动到该元素。请参阅下面的示例:
A) http://localhost:4200/#/test/test-history
B) http://localhost:4200/#/test/test-history#orderhistory
当我输入 A) 时,我想要没有滚动效果的正常页面加载。
当我输入 B) 时,我想通过滚动到元素来加载页面。
在HTML中,我做了<div #orderhistory id="orderhistory" *ngIf="requestForCostShipment" >Bla Bla </div>
并且在 .ts 文件中,在 ngOnInit()
下,我执行了以下操作:
this.scroll('orderhistory');
我在下面写了一个函数:
scroll(id) {
let el = document.getElementById(id);
el.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
}
但是,我遇到了错误:
Cannot read property 'scrollIntoView' of null
我看到了几个 post 并应用了几个方法 scrollToBottom();
但没有运气。
感谢任何帮助。
修改:
ngAfterViewInit() {
// Scroll (Anchor) Function to Order History
this.scroll('orderhistory');
}
上面还是显示错误
Cannot read property 'scrollIntoView' of null
问题是您的 el
尚未渲染。其原因可能是当 DOM 中不存在元素时从 ngOnInit
调用 this.scroll
。您应该在 ngAfterViewInit
中调用 scroll
方法,该方法在视图初始化后调用一次。
因为有一个显示 div 的条件,所以当 requestForCostShipment
的值为 true 时,您需要调用滚动函数,像这样
ngAfterViewInit() {
// Scroll (Anchor) Function to Order History
if(this.requestForCostShipment){
this.scroll('orderhistory');
}
}
或调用 this.scroll('orderhistory');
,其中 requestForCostShipment
的值设置为 true
。
我想在页面加载时将页面滚动到该元素。请参阅下面的示例:
A) http://localhost:4200/#/test/test-history
B) http://localhost:4200/#/test/test-history#orderhistory
当我输入 A) 时,我想要没有滚动效果的正常页面加载。 当我输入 B) 时,我想通过滚动到元素来加载页面。
在HTML中,我做了<div #orderhistory id="orderhistory" *ngIf="requestForCostShipment" >Bla Bla </div>
并且在 .ts 文件中,在 ngOnInit()
下,我执行了以下操作:
this.scroll('orderhistory');
我在下面写了一个函数:
scroll(id) {
let el = document.getElementById(id);
el.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
}
但是,我遇到了错误:
Cannot read property 'scrollIntoView' of null
我看到了几个 post 并应用了几个方法 scrollToBottom();
但没有运气。
感谢任何帮助。
修改:
ngAfterViewInit() {
// Scroll (Anchor) Function to Order History
this.scroll('orderhistory');
}
上面还是显示错误
Cannot read property 'scrollIntoView' of null
问题是您的 el
尚未渲染。其原因可能是当 DOM 中不存在元素时从 ngOnInit
调用 this.scroll
。您应该在 ngAfterViewInit
中调用 scroll
方法,该方法在视图初始化后调用一次。
因为有一个显示 div 的条件,所以当 requestForCostShipment
的值为 true 时,您需要调用滚动函数,像这样
ngAfterViewInit() {
// Scroll (Anchor) Function to Order History
if(this.requestForCostShipment){
this.scroll('orderhistory');
}
}
或调用 this.scroll('orderhistory');
,其中 requestForCostShipment
的值设置为 true
。