ScrollTop 设置属性在 angular 中不起作用

问题描述

大家早上好, 我正在尝试使用 angular 创建实时聊天,我必须设置用户在包装器底部滚动的视图,其中有聊天元素。 我已经使用了一些技巧,但是 scrollTop 属性没有连续设置。

这是我的 html 模板:

<section #chat class="chat-wrapper" id="chat">
    <div *ngFor="let message of this.messageList" #item>
         . . .
    </div>
</section>

"chat-wrapper" 具有 "overflow-y:scroll" 属性

这是打字稿:

@Component({
  selector: 'chat-page',templateUrl: './chat-page.component.html',styleUrls: ['./chat-page.component.css'],})
export class ChatPageComponent implements AfterViewInit,AfterContentinit {

  messageList;
  private scrollContainer: any;
  scrolltop: number = null;

  @ViewChild('chat',{ read: ElementRef,static: false }) scrollFrame: ElementRef;
  @ViewChildren('item') itemElements: QueryList<any>;

  constructor(private socketService: SocketService,public global: Global,private route: ActivatedRoute) {

    this.socketService.getChat(this.id,this.global.cookie,this.number).subscribe((msg) => {

      // HERE I GET THE OLD MESSAGES

      this.socketService.startListen(this.id).subscribe((msg) => {
        // HERE I GET THE NEW MESSAGES
      });

    });
  }

  ngAfterViewInit() {
    this.scrollContainer = this.scrollFrame.nativeElement;
    this.scrollToBottom();
    this.itemElements.changes.subscribe(_ => this.onItemElementsChanged());
  }

  private onItemElementsChanged(): void {
    this.scrollToBottom();
  }

  ngAfterViewChecked() {
    this.scrollToBottom()
    this.itemElements.changes.subscribe(_ => this.onItemElementsChanged());
  }

  private scrollToBottom(): void {
    this.scrollContainer.scroll({
      top: this.scrollContainer.scrollHeight,left: 0,behavior: 'smooth'
    });
  }
}

这是我找到并测试的最后一种方法……但不起作用。我也试过 scrollTop=scrollHeight。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)