अपना समाधान साझा कर रहा हूं, क्योंकि मैं बाकी लोगों से पूरी तरह संतुष्ट नहीं था। इसके साथ मेरी समस्या AfterViewCheckedयह है कि कभी-कभी मैं स्क्रॉल कर रहा हूं, और किसी कारण से, यह जीवन हुक कहा जाता है और यह मुझे नीचे स्क्रॉल करता है, भले ही कोई नया संदेश न हो। मैंने उपयोग करने की कोशिश की OnChangesलेकिन यह एक मुद्दा था, जिसने मुझे इस समाधान की ओर अग्रसर किया । दुर्भाग्य से, केवल उपयोग करने से, DoCheckयह संदेश दिए जाने से पहले स्क्रॉल कर रहा था, जो या तो उपयोगी नहीं था, इसलिए मैंने उन्हें जोड़ दिया ताकि DoCheck मूल रूप से संकेत दे रहा है AfterViewCheckedकि क्या यह कॉल करना चाहिए scrollToBottom।
प्रतिक्रिया पाकर खुशी हुई।
export class ChatComponent implements DoCheck, AfterViewChecked {
@Input() public messages: Message[] = [];
@ViewChild('scrollable') private scrollable: ElementRef;
private shouldScrollDown: boolean;
private iterableDiffer;
constructor(private iterableDiffers: IterableDiffers) {
this.iterableDiffer = this.iterableDiffers.find([]).create(null);
}
ngDoCheck(): void {
if (this.iterableDiffer.diff(this.messages)) {
this.numberOfMessagesChanged = true;
}
}
ngAfterViewChecked(): void {
const isScrolledDown = Math.abs(this.scrollable.nativeElement.scrollHeight - this.scrollable.nativeElement.scrollTop - this.scrollable.nativeElement.clientHeight) <= 3.0;
if (this.numberOfMessagesChanged && !isScrolledDown) {
this.scrollToBottom();
this.numberOfMessagesChanged = false;
}
}
scrollToBottom() {
try {
this.scrollable.nativeElement.scrollTop = this.scrollable.nativeElement.scrollHeight;
} catch (e) {
console.error(e);
}
}
}
chat.component.html
<div class="chat-wrapper">
<div class="chat-messages-holder" #scrollable>
<app-chat-message *ngFor="let message of messages" [message]="message">
</app-chat-message>
</div>
<div class="chat-input-holder">
<app-chat-input (send)="onSend($event)"></app-chat-input>
</div>
</div>
chat.component.sass
.chat-wrapper
display: flex
justify-content: center
align-items: center
flex-direction: column
height: 100%
.chat-messages-holder
overflow-y: scroll !important
overflow-x: hidden
width: 100%
height: 100%