Skip to content

Commit

Permalink
Fixed #15524 - Fix dialog bug
Browse files Browse the repository at this point in the history
  • Loading branch information
cetincakiroglu committed May 10, 2024
1 parent 8aaee7a commit 45a76b8
Showing 1 changed file with 32 additions and 15 deletions.
47 changes: 32 additions & 15 deletions src/app/components/autofocus/autofocus.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand All @@ -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) {
Expand All @@ -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({
Expand Down

0 comments on commit 45a76b8

Please sign in to comment.