UtilAdded in v16.6Optional

wrFocusFirstInvalid

After a refused submit, focuses the first invalid control and scrolls its field into view.

Usage

Call it after submit() or markAllAsTouched(), with an injector: it waits for the render that draws the errors.

import { Component, ElementRef, Injector, inject, signal, viewChild } from '@angular/core';
import { FormField, form, required, submit } from '@angular/forms/signals';

import { wrFocusFirstInvalid } from 'ngwr/utils';

@Component({
  template: `
    <form #formEl (submit)="$event.preventDefault(); save()">
      <wr-form-field label="Name">
        <input wrInput [formField]="profile.name" />
      </wr-form-field>
      <button wr-btn type="submit">Save</button>
    </form>
  `,
})
export class Profile {
  private readonly injector = inject(Injector);
  private readonly formEl = viewChild.required<ElementRef<HTMLElement>>('formEl');

  private readonly model = signal({ name: '' });
  protected readonly profile = form(this.model, path => {
    required(path.name, { message: 'Enter a name.' });
  });

  protected async save(): Promise<void> {
    const sent = await submit(this.profile, async () => this.api.save(this.model()));
    if (!sent) void wrFocusFirstInvalid(this.formEl().nativeElement, { injector: this.injector });
  }
}

Rules

CaseResult
What counts as invalid An element with aria-invalid="true", or a <wr-form-field> showing an error.
A group, such as wr-radio-groupThe first control inside it takes the focus.
Disabled or hiddenSkipped.
ScrollThe field goes to the centre, smoothly. Under prefers-reduced-motion it jumps.
No injectorIt looks at once. Use it when the errors are already on screen.
On the serverDoes nothing and resolves to false.

API

NameDescriptionTypeDefault
wrFocusFirstInvalid(root, options?)Focuses the first invalid control inside root and scrolls its field into view. Resolves to whether there was one.(root: HTMLElement, options?: WrFocusFirstInvalidOptions) => Promise<boolean>-
options.injectorWaits for the next render before looking. Pass it when the call follows the submit.Injector-
options.scrollOptions for scrollIntoView, or false to leave the scroll to the browser. Reduced motion always jumps.ScrollIntoViewOptions | false{ block: 'center', behavior: 'smooth' }

See also