如何自动向下滚动到div的底部

问题描述 投票:0回答:1

我有一个 Angular 聊天应用程序,我正在尝试像大多数聊天应用程序一样向下滚动到底部。我尝试了本机

element.scrollTop
属性,但它对我不起作用。

搜索.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
/* ... */

@Component({ /* ... */ })
export class SearchComponent {
  @ViewChild('inboxChat', { static: true })
  inboxChat?: ElementRef<HTMLDivElement>;

  constructor(private socketService: SearchService, private router: Router) {}

  ngOnInit() { 
    if (this.inboxChat?.nativeElement) {
      this.inboxChat.nativeElement.scrollTop = this.inboxChat.nativeElement.scrollHeight;
    }
  }

  ngAfterViewInit() {
    if (this.inboxChat?.nativeElement) {
      this.inboxChat.nativeElement.scrollTop = this.inboxChat.nativeElement.scrollHeight;
    }
  }
}
search.component.html
<div class="mesgs" *ngIf="selectedMessages !== []">
  <div #inboxChat class="msg_history">
    <!-- ... -->
  </div>
</div>
搜索.组件.css
/* ... */
.msg_history {
  height: 516px;
  overflow-y: auto;
}

.msgs
类根本没有
overflow-y
,我也尝试选择该类。

angular
1个回答
0
投票

我认为

*ngIf
条件不会导致子视图正确初始化。

将其更改为使用

[hidden]
,以便子视图被初始化并且逻辑触发滚动到底部。

<div  class="mesgs" [hidden]="!selectedMessages.length">
  <div #inboxChat class="msg_history">
    @for(item of  selectedMessages; track $index) {
      <div>{{item}}</div>
    }
  </div>
</div>

完整代码:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: `
    <div  class="mesgs" [hidden]="!selectedMessages.length">
      <div #inboxChat class="msg_history">
        @for(item of  selectedMessages; track $index) {
          <div>{{item}}</div>
        }
      </div>
    </div>
  `,
})
export class App {
  selectedMessages: any[] = new Array(10000).fill(0).map((_, i: any) => i);
  @ViewChild('inboxChat', { static: true })
  inboxChat?: ElementRef<HTMLDivElement>;

  ngAfterViewInit() {
    // Accessing the DOM element directly
    console.log(this.inboxChat?.nativeElement);
    // Modifying the DOM element
    if (this.inboxChat?.nativeElement)
      this.inboxChat.nativeElement.scrollTop =
        this.inboxChat?.nativeElement.scrollHeight;
  }
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.