Please don't mark this as duplicate, I have tried other solutions and their answers did not work and it is not the same.
It works fine on first focus sometimes as you can see in the below gif, but in subsequent focuses the input starts scrolling down as new messages are added:-
.gif
Demo using remote debugger:-
.gif
appponnent.ts
import { isPlatformBrowser } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit, PLATFORM_ID, signal } from '@angular/core';
@Component({
selector: 'app-root',
imports: [],
templateUrl: './appponent.html',
styleUrl: './appponent.scss'
})
export class AppComponent implements OnInit, OnDestroy {
messages = signal<string[]>([]);
intervalId: any;
counter = 1;
constructor() {}
ngOnInit(): void {
this.intervalId = setInterval(() => {
this.messages.set([...this.messages(), 'test'+this.counter++]);
}, 2000);
}
ngOnDestroy() {
if (this.intervalId) {
clearInterval(this.intervalId); // Cleanup to prevent memory leaks
}
}
}
appponent.html
<div class="container">
<!-- HEADER -->
<header class="header">
Banner
</header>
<!-- HEADER END -->
<!-- CHAT SCREEN -->
<div class="screen">
<!-- MESSAGES -->
<div class="messages">
@for (message of messages(); track $index) {
<!-- Message -->
<div class="message" [style.order]="messages().length-$index">
<div class="message">
<div class="message-inner">{{ message }}</div>
</div>
</div>
<!-- Message end -->
}
</div>
<!-- MESSAGES END -->
<!-- CONTROLLER -->
<div class="controller">
<form class="controller-form">
<input class="controller-input" type="text">
<button type="submit">
Submit
</button>
</form>
</div>
<!-- CONTROLLER END -->
</div>
<!-- CHAT SCREEN END -->
</div>
<!-- CHAT SCREEN END -->
appponent.scss
.container {
display: flex;
flex-direction: column;
height: 100dvh;
background-color: yellow;
}
.header {
min-height: 1rem;
display: flex;
align-items: center;
position: sticky;
top: 0;
background-color: burlywood;
}
.screen {
display: flex;
flex-direction: column;
flex-grow: 1;
overflow-y: auto;
}
.messages {
display: flex;
flex-direction: column-reverse;
gap: 1rem;
padding: 0.5rem;
flex: 1;
overflow-y: auto;
}
.message {
display: flex;
}
.message-inner {
background-color: aqua;
padding: 0.5rem;
}
.controller {
display: flex;
gap: 1;
margin-bottom: 0.25rem;
position: sticky;
bottom: 0;
}
.controller-form {
display: flex;
gap: 1;
}
.controller-input {
display: flex;
flex-grow: 1;
border: 2px;
justify-self: center;
padding: 0.25rem;
}
styles.scss
body {
margin: 0;
}