From 45a76b8a166b720ba44922ac690fb4c8b6e02b5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87etin?= <69278826+cetincakiroglu@users.noreply.github.com> Date: Fri, 10 May 2024 15:20:41 +0300 Subject: [PATCH] Fixed #15524 - Fix dialog bug --- src/app/components/autofocus/autofocus.ts | 47 +++++++++++++++-------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/app/components/autofocus/autofocus.ts b/src/app/components/autofocus/autofocus.ts index 11253f8051b..9b218a7cc84 100644 --- a/src/app/components/autofocus/autofocus.ts +++ b/src/app/components/autofocus/autofocus.ts @@ -1,5 +1,5 @@ -import { CommonModule } from '@angular/common'; -import { Directive, ElementRef, Input, NgModule, booleanAttribute } from '@angular/core'; +import { CommonModule, DOCUMENT, isPlatformBrowser } from '@angular/common'; +import { Directive, ElementRef, Input, NgModule, PLATFORM_ID, booleanAttribute, inject } from '@angular/core'; import { DomHandler } from 'primeng/dom'; /** * AutoFocus manages focus on focusable element on load. @@ -12,7 +12,6 @@ import { DomHandler } from 'primeng/dom'; } }) export class AutoFocus { - constructor(private host: ElementRef) {} /** * When present, it specifies that the component should automatically get focus on load. * @group Props @@ -21,6 +20,12 @@ export class AutoFocus { focused: boolean = false; + platformId = inject(PLATFORM_ID); + + document: Document = inject(DOCUMENT); + + host: ElementRef = inject(ElementRef); + ngAfterContentChecked() { // This sets the `attr.autofocus` which is different than the Input `autofocus` attribute. if (this.autofocus === false) { @@ -31,21 +36,33 @@ export class AutoFocus { if (!this.focused) { if (this.autofocus) { - setTimeout(() => { - const focusableElements = DomHandler.getFocusableElements(this.host.nativeElement); - - if (focusableElements.length === 0) { - this.host.nativeElement.focus(); - } - if (focusableElements.length > 0) { - focusableElements[0].focus(); - } - - this.focused = true; - }); + this.focus(); } } } + + ngAfterViewChecked() { + if (!this.focused) { + this.focus(); + } + } + + focus() { + if (isPlatformBrowser(this.platformId)) { + setTimeout(() => { + const focusableElements = DomHandler.getFocusableElements(this.host?.nativeElement); + + if (focusableElements.length === 0) { + this.host.nativeElement.focus(); + } + if (focusableElements.length > 0) { + focusableElements[0].focus(); + } + + this.focused = true; + }); + } + } } @NgModule({