【问题标题】:Angular 2 scrollIntoView Not ScrollingAngular 2 scrollIntoView 不滚动
【发布时间】:2019-05-13 09:50:09
【问题描述】:

我的 HTML 中有一个 ID 为 footerWrapperTop 的 DIV。

我的组件中有以下 TypeScript:

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

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

    请检查这个问题:How to call scrollIntoView on an element in angular 2+

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

    <div #footerWrapperTop></div>
    

    在component.ts中:

    export class MyComponent {
      @ViewChild("footerWrapperTop") MyProp: ElementRef;
    
      ngAfterViewInit() {
        this.MyProp.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }
    

    但是,当路由器发生变化时,angular 5 及更低版本存在错误。 Angular 6 已经解决了这个问题。检查这个问题:https://github.com/angular/angular/issues/7791

    【讨论】:

    • 使用Renderer2更安全
    【解决方案2】:

    您可以使用 Angular 的渲染器

    根据Angular's Official Documentation 为 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
    
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 2020-10-24
      • 2014-08-31
      • 2020-10-17
      • 2021-06-16
      • 2020-02-20
      • 2019-03-17
      • 2022-10-18
      相关资源
      最近更新 更多