![](/img/trans.png)
[英]TypeError: Cannot read property 'scrollIntoView' of null How to solve?
[英]How to solve "Cannot read property 'scrollIntoView' of undefined"?
我想在单击Angular 7 中的按钮时滚动到特定的 div,下面是我正在使用的代码,但它在 stackblitz 中工作,但在我的项目中使用时显示错误。 “无法读取未定义的属性‘scrollIntoView’”。
https://stackblitz.com/edit/angular-scroll-local-variable?file=src%2Fapp%2Fscroll.component.ts
试试这个链接: https : //stackblitz.com/edit/angular-scroll-local-variable-ja96uz?file=src%2Fapp%2Fapp.component.html
<button (click)="scroll(target)"></button>
<div #target>Your target</div>
并在组件中:
scroll(el) {
el.scrollIntoView();
}
尝试提供 scrollToAnchor 方法的 angular ViewportScroller 服务
滚动.html
<button (click)="scroll('target')">Click to scroll</button>
<div id="target">Your target</div>
scroll.ts
import { Component, Input } from '@angular/core';
import { ViewportScroller } from '@angular/common';
@Component({
selector: 'scroll',
template: `
<button (click)="scroll('target')">Click to scroll</button>
<div id="target">Your target</div>
`,
styles: [`h1 { font-family: Lato; }`, `div { margin-top: 5000px; }`]
})
export class ScrollComponent {
constructor(private vps: ViewportScroller) {
}
scroll(id) {
this.vps.scrollToAnchor(id);
}
}
示例: https : //stackblitz.com/edit/angular-scroll-local-variable-99hwvo
尝试使用 ViewChild:
//HTML
<button (click)="scroll()"></button><div #target>Your target</div>
//ts
//Import
import { ..., ViewChild, ElementRef } from '@angular/core';
//Declare
@ViewChild('target') targetEl: ElementRef;
scroll() {
this.targetEl.nativeElement.scrollIntoView();
}
滚动.html
<button (click)="scroll()">Click to scroll</button>
<div id="target">Your target</div>
组件
getOffset(el) {
el = el.getBoundingClientRect();
return {
left: el.left + window.scrollX,
top: el.top + window.scrollY,
bottom: el.top + window.scrollY
}
}
scroll() {
var scroll_to = document.getElementById('target');
var topHight = this.getOffset(scroll_to).top;
window.scrollTo(0, topHight);
}
由于*ngIf
条件,代码*ngIf
,当您使用show
变量时默认设置为false
,因此组件上不会呈现div 。
代码应该用在要滚动的相关组件中,例如:
如果您在滚动组件中需要,则
HTML:
<button (click)="scroll(target)">clicking this button</button>
<div style="marging-top: 100px; height: 900px;"></div>
<div #target *ngIf="show" style="border: 1px solid #000; padding: 10px;margin-top: 10px;">
show get screen scrolled to this div
</div>
TS:
scroll(el: HTMLElement) {
if(el){ // If the div is rendered on the HTML then it should be HTML element
el.scrollIntoView();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.