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({