在Angular 2中,可以使用ViewChild装饰器来引用DOM元素并调用其scrollIntoView方法。以下是一个示例解决方法:
首先,在组件的模板中,添加一个按钮和一个需要滚动到的目标元素:
然后,在组件的类中,使用ViewChild装饰器引用目标元素,并在点击按钮时调用scrollIntoView方法:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent {
@ViewChild('scrollTarget', {static: false}) scrollTarget: ElementRef;
scrollToElement() {
this.scrollTarget.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
在上面的代码中,scrollTarget被装饰为ViewChild,并且在scrollToElement方法中,我们通过nativeElement属性来访问DOM元素,并调用其scrollIntoView方法来滚动到元素。
最后,当点击按钮时,scrollToElement方法将被调用,目标元素将滚动到视图中。
请注意,确保在引用DOM元素之前,ViewChild装饰器的第二个参数设置为false。这是因为在这个示例中,目标元素是通过ngIf等指令动态地添加到DOM中的。