如何解决“无法读取未定义的属性‘scrollIntoView’”?

新手上路,请多包涵

我想在单击 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();
}

原文由 mani singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 350
1 个回答

尝试提供 scrollToAnchor 方法的角度 ViewportScroller 服务

滚动.html

 <button (click)="scroll('target')">Click to scroll</button>
<div id="target">Your target</div>

滚动.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

原文由 Chellappan வ 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题