如何在Angle 2+中的元素上调用scrollIntoView [英] How to call scrollIntoView on an element in angular 2+

查看:264
本文介绍了如何在Angle 2+中的元素上调用scrollIntoView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML上调用 scrollIntoView 组件中的元素.

I want to call scrollIntoView on a HTML element in a component.

在angular.js 1中,我可以在控制器中执行以下操作:

In angular.js 1 I can do something like this in the controller:

var element = $window.document.getElementById(id);
element.scrollIntoView({ behavior: "smooth", block: "start" });

我该如何在Angle 2+中做同样的事情?

How can I do the same thing in angular 2+ ?

推荐答案

首先在元素(#myElem)中添加模板引用变量:

First add a template reference variable in the element (the #myElem):

<p #myElem>Scroll to here!</p>

然后在具有属性ViewChild的组件中创建一个属性,并在其上调用.nativeElement.scrollIntoView:

Then create a property in the component with attribute ViewChild, and call .nativeElement.scrollIntoView on it:

export class MyComponent {
  @ViewChild("myElem") MyProp: ElementRef;

  ngOnInit() {
    this.MyProp.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
  }
}

这篇关于如何在Angle 2+中的元素上调用scrollIntoView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆