Skip to content

Commit 4e82db5

Browse files
committed
fix(cdk/text-field): Long multiline textfield focus issue.
When we have long multiline textfield and put cursor on almost an end (For eg. on 3rd last line) the scroll moves up to the top of textarea. This fix will listen to scroll event and update the `scrollTop` in `resizeToFitContent` method Fixes #20255
1 parent ef62d5c commit 4e82db5

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

src/cdk/text-field/autosize.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export class CdkTextareaAutosize implements AfterViewInit, DoCheck, OnDestroy {
4747

4848
/** Keep track of the previous textarea value to avoid resizing when the value hasn't changed. */
4949
private _previousValue?: string;
50+
private _currentScrollTop: number;
5051
private _initialHeight: string | undefined;
5152
private readonly _destroyed = new Subject<void>();
5253
private _listenerCleanups: (() => void)[] | undefined;
@@ -164,6 +165,7 @@ export class CdkTextareaAutosize implements AfterViewInit, DoCheck, OnDestroy {
164165
this._renderer.listen('window', 'resize', () => this._resizeEvents.next()),
165166
this._renderer.listen(this._textareaElement, 'focus', this._handleFocusEvent),
166167
this._renderer.listen(this._textareaElement, 'blur', this._handleFocusEvent),
168+
this._renderer.listen(this._textareaElement, 'scroll', this._handleScrollEvent),
167169
];
168170
this._resizeEvents.pipe(auditTime(16)).subscribe(() => {
169171
// Clear the cached heights since the styles can change
@@ -284,6 +286,10 @@ export class CdkTextareaAutosize implements AfterViewInit, DoCheck, OnDestroy {
284286
this._hasFocus = event.type === 'focus';
285287
};
286288

289+
private _handleScrollEvent = (event: Event) => {
290+
this._currentScrollTop = (event?.target as HTMLTextAreaElement)?.scrollTop;
291+
};
292+
287293
ngDoCheck() {
288294
if (this._platform.isBrowser) {
289295
this.resizeToFitContent();
@@ -323,6 +329,7 @@ export class CdkTextareaAutosize implements AfterViewInit, DoCheck, OnDestroy {
323329

324330
// Use the scrollHeight to know how large the textarea *would* be if fit its entire value.
325331
textarea.style.height = `${height}px`;
332+
textarea.scrollTop = this._currentScrollTop;
326333

327334
this._ngZone.runOutsideAngular(() => {
328335
if (typeof requestAnimationFrame !== 'undefined') {

0 commit comments

Comments
 (0)