【问题标题】:auto scroll to bottom directive doesn't work in angular 2自动滚动到底部指令在角度 2 中不起作用
【发布时间】:2018-06-26 13:41:54
【问题描述】:

我正在创建一个聊天应用程序,我需要在其中实现自动滚动到文本消息的底部。 div 应该在页面的初始加载和重新加载时完成。我创建了一个自定义指令来实现这一点。但是,这似乎不起作用。

指令:

import { Directive,ElementRef,AfterViewInit} from '@angular/core';


@Directive({ selector: '[scrollToBottom]' })
export class ScrollToBottomDirective implements AfterViewInit {
    constructor(private element:ElementRef) {
        console.log('scroll', this.element);
    }
    ngAfterViewInit(){
        this.scrollToBottom();
    }
    scrollToBottom(){
        if(this.element){
            (this.element as any).nativeElement.scrollTop =(this.element as any).nativeElement.scrollHeight;
            console.log('scroll', (this.element as any).nativeElement.scrollTop) 
            console.log('scrollHeight', (this.element as any).nativeElement.scrollHeight) 
        }
    }
}

我哪里做错了?

【问题讨论】:

    标签: html angular


    【解决方案1】:

    你可以试试这样的

    ScrollToBottom() {
        if(this.element){
           // I can't remember why I added a short timeout, 
           // the below works great though. 
           if(this.element != undefined){
              setTimeout(() => { element.scrollIntoView(true) }, 200);
           }
        }
    
     }
    

    【讨论】:

      【解决方案2】:

      我通过将生命周期挂钩从“AfterViewInit”更改为“afterViewChecked”事件来修复它

      【讨论】:

        【解决方案3】:

        另外,如果你需要滚动一次底部,我推荐下一个解决方案:

        import { Directive, ElementRef, AfterViewChecked, HostListener } from '@angular/core';
        
        @Directive({
          selector: '[scrollToBottom]'
        })
        export class ScrollToBottomDirective implements AfterViewChecked {
          isActive = true;
        
          @HostListener('scroll') onFrameScroll() {
            this.isActive = false;
          }
        
          constructor(private element: ElementRef) {}
        
          ngAfterViewChecked() {
            this.scrollToBottom();
          }
        
          scrollToBottom() {
            if (this.element && this.isActive) {
              this.element.nativeElement.scrollTop = this.element.nativeElement.scrollHeight;
            }
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-01-25
          • 1970-01-01
          • 1970-01-01
          • 2021-12-05
          • 2023-02-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-03
          相关资源
          最近更新 更多