8000 add default touched event logic for ui controls by mmalerba · Pull Request #61288 · angular/angular · GitHub
[go: up one dir, main page]

Skip to content

add default touched event logic for ui controls #61288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions packages/forms/experimental/src/controls/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
InputSignal,
OutputEmitterRef,
OutputRef,
OutputRefSubscription,
untracked,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl} from '@angular/forms';
Expand All @@ -38,7 +39,7 @@ import {InteropNgControl} from './interop_ng_control';
export class FieldDirective<T> {
readonly injector = inject(Injector);
readonly field = input.required<Field<T>>();
readonly el = inject(ElementRef);
readonly el: ElementRef<HTMLElement> = inject(ElementRef);
readonly cvaArray = inject<ControlValueAccessor[]>(NG_VALUE_ACCESSOR, {optional: true});

private _ngControl: InteropNgControl | undefined;
Expand Down Expand Up @@ -107,12 +108,28 @@ export class FieldDirective<T> {
const cleanupValue = cmp.value.subscribe((newValue) =>
this.field().$state.value.set(newValue),
);
const cleanupTouch = cmp.touch?.subscribe(() => this.field().$state.markAsTouched());
let cleanupTouch: OutputRefSubscription | undefined;
let cleanupDefaultTouch: (() => void) | undefined;
if (cmp.touch !== undefined) {
cleanupTouch = cmp.touch.subscribe(() => this.field().$state.markAsTouched());
} else {
// If the component did not give us a touch event stream, use the standard touch logic,
// marking it touched when the focus moves from inside the host element to outside.
const listener = (event: FocusEvent) => {
const newActiveEl = event.relatedTarget;
if (!this.el.nativeElement.contains(newActiveEl as Element | null)) {
this.field().$state.markAsTouched();
}
};
this.el.nativeElement.addEventListener('focusout', listener);
cleanupDefaultTouch = () => this.el.nativeElement.removeEventListener('focusout', listener);
}

// Cleanup for output binding subscriptions:
injector.get(DestroyRef).onDestroy(() => {
cleanupValue.unsubscribe();
cleanupTouch?.unsubscribe();
cleanupDefaultTouch?.();
});
} else {
throw new Error(`Unhandled control?`);
Expand Down
Loading
0