diff --git a/projects/coreui-angular/src/lib/modal/modal/modal.component.spec.ts b/projects/coreui-angular/src/lib/modal/modal/modal.component.spec.ts index 8b10774d..98b6facb 100644 --- a/projects/coreui-angular/src/lib/modal/modal/modal.component.spec.ts +++ b/projects/coreui-angular/src/lib/modal/modal/modal.component.spec.ts @@ -1146,6 +1146,15 @@ describe('ModalComponent on the server', () => { afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('should open without moving focus', () => { + const focus = vi.spyOn(HTMLElement.prototype, 'focus'); + component.visible.set(true); + fixture.detectChanges(); + expect(() => vi.runAllTimers()).not.toThrow(); + expect(focus).not.toHaveBeenCalled(); }); it('should release the lock and modal-open as it closes, with no render to wait for', () => { diff --git a/projects/coreui-angular/src/lib/modal/modal/modal.component.ts b/projects/coreui-angular/src/lib/modal/modal/modal.component.ts index 6482f37f..33764349 100644 --- a/projects/coreui-angular/src/lib/modal/modal/modal.component.ts +++ b/projects/coreui-angular/src/lib/modal/modal/modal.component.ts @@ -208,11 +208,13 @@ export class ModalComponent implements OnInit, OnDestroy, AfterViewInit { untracked(() => { if (visible && afterViewInit) { this.#focusBeforeShow = this.#document.activeElement as HTMLElement | null; - setTimeout(() => { - if (!this.focusTrap()?.focusTrap.focusInitialElement()) { - this.#hostElement.nativeElement.focus(); - } - }); + if (isPlatformBrowser(this.#platformId)) { + setTimeout(() => { + if (!this.focusTrap()?.focusTrap.focusInitialElement()) { + this.#hostElement.nativeElement.focus(); + } + }); + } } else { this.#restoreFocus(); }