首页 > 解决方案 > Angular 2 scrollIntoView 不滚动

问题描述

footerWrapperTop我的HTML 中有一个 id 的 DIV 。

我的组件中有以下 TypeScript:

  ngAfterViewInit(): void {
    try {
      this.sFragment = 'footerWrapperTop';
      const nativeElement = document.querySelector('#' + this.sFragment);
      nativeElement.scrollIntoView();
    } catch (e) { }   }

但是,页面在运行时不会向下滚动到页脚。我究竟做错了什么?

如果我console.dir(nativeElement);在控制台中显示 DIV。

标签: angular

解决方案


您可以使用Angular 的渲染器

根据Angular 的官方文档为 selectRootElement提供第二个参数,因为它用于保存您的内容

句法: selectRootElement(selectorOrNode: any, preserveContent?: boolean): any

已创建Stackblitz Demo供您参考

import { Component, AfterViewInit, Renderer2 } from '@angular/core';


@Component({...})
export class ChildComponent implements AfterViewInit {

  sFragment: string;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit(): void {
      this.sFragment = 'footerWrapperTop';

      const element = this.renderer.selectRootElement(`#${this.sFragment}`, true); // true to indicate that you will preserve the content

      element.scrollIntoView({ behavior: 'smooth' });   // for smooth scrolling

  }

}

推荐阅读