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 });
}
}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.
Rules
| Case | Result |
|---|---|
| What counts as invalid | An element with aria-invalid="true", or a <wr-form-field> showing an error. |
A group, such as wr-radio-group | The first control inside it takes the focus. |
| Disabled or hidden | Skipped. |
| Scroll | The field goes to the centre, smoothly. Under prefers-reduced-motion it jumps. |
No injector | It looks at once. Use it when the errors are already on screen. |
| On the server | Does nothing and resolves to false. |
API
| Name | Description | Type | Default |
|---|---|---|---|
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.injector | Waits for the next render before looking. Pass it when the call follows the submit. | Injector | - |
options.scroll | Options for scrollIntoView, or false to leave the scroll to the browser. Reduced motion always jumps. | ScrollIntoViewOptions | false | { block: 'center', behavior: 'smooth' } |
See also
Guide FormsBind ngwr controls to any Angular form and show their errors.Directive wrAutofocusFocus an element on init, or each time a binding turns true.Component Form FieldWraps a form control with a label, a hint and its error messages.Util wrGetFocusableElementsLists the focusable descendants of an element, in DOM order.