代码之家  ›  专栏  ›  技术社区  ›  dota2pro Matej

如何在添加元素时滚动到NgFor中元素的底部?

  •  0
  • dota2pro Matej  · 技术社区  · 7 年前
    import { Component, Input, AfterViewInit, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'hello',
      template: `<h1>Hello {{name}}!</h1>
    
      <div #commentDetailWrapper style="height: 100px; border: 1px solid; width: 100px; overflow-y:scroll ">
    
    <div *ngFor="let axe of axes"><button>Filler</button></div>
    
      </div>
      <button (click)='add()'>Add More</button>
    
    
      `,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent implements AfterViewInit {
      @Input() name: string;
      @ViewChild('commentDetailWrapper', { static: false }) commentDetailWrapper;
    
      axes = Array(10);
    
      add() {
        this.axes.push(Array(1));
        const el: HTMLDivElement = this.commentDetailWrapper.nativeElement;
        el.scrollTop = el.scrollHeight;
      }
    
      ngAfterViewInit() {
        const el: HTMLDivElement = this.commentDetailWrapper.nativeElement;
        el.scrollTop = el.scrollHeight;
      }
    
    }
    

    默认情况下,它会滚动到最后一个元素当我通过单击 add More 按钮

    下面是演示的问题 Stackblitz

    所需结果:单击“添加更多”按钮滚动到底部

    1 回复  |  直到 7 年前
        1
  •  1
  •   ajai Jothi    7 年前

    超时后执行滚动可以解决问题。因为在您尝试滚动时视图不会更新。

    解决方案1: 使用 AfterViewChecked

    export class HelloComponent implements AfterViewInit, AfterViewChecked {
    added:boolean;
     ...
       add() {
        this.axes.push(Array(1));
        this.added = true;
      }
    
      ngAfterViewChecked() {
       // run only when new axe is added
       if(this.added) {
        const el: HTMLDivElement = this.commentDetailWrapper.nativeElement;
        el.scrollTop = el.scrollHeight;
        this.added = false;
       }
      }
    ...
    }
    

    解决方案2: 使用 setTimeout ,则,

    ...
    add() {
       this.axes.push(Array(1));
       const el: HTMLDivElement = this.commentDetailWrapper.nativeElement;
       setTimeout(() => {
         el.scrollTop = el.scrollHeight;
       });
    }
    ...
    

    解决方案1a: 分离组件并使输入数据不可变。习惯于 ChangeDetectionStrategy.OnPush 用于实施

    https://stackblitz.com/edit/angular-2zjf4a

    推荐文章