我有一个 Angular 聊天应用程序,我正在尝试像大多数聊天应用程序一样向下滚动到底部。我尝试了本机
element.scrollTop
属性,但它对我不起作用。
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;
}
}
}
<div class="mesgs" *ngIf="selectedMessages !== []">
<div #inboxChat class="msg_history">
<!-- ... -->
</div>
</div>
/* ... */
.msg_history {
height: 516px;
overflow-y: auto;
}
.msgs
类根本没有overflow-y
,我也尝试选择该类。
我认为
*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);