Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/primefaces/primeng
Browse files Browse the repository at this point in the history
  • Loading branch information
mehmetcetin01140 committed May 10, 2024
2 parents 43d889e + 31e6aa7 commit bcca799
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 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 @@ -30,20 +35,30 @@ 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.autoFocus();
}
}

ngAfterViewChecked() {
if (!this.focused) {
this.autoFocus();
}
}

autoFocus() {
if (isPlatformBrowser(this.platformId) && 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;
});
}
}
}
Expand Down

0 comments on commit bcca799

Please sign in to comment.