perf(forms): use addEventListener to avoid unconditional CD scheduling on blur

Previously, the blur and input listeners in nativeControlCreate were
registered via host.listenToDom(), which routes through wrapListener and
calls markViewDirty before running the callback. This caused
scheduler.notify() to fire on every blur event, even when the control was
already touched and the signal write was a no-op.

Switch to native addEventListener so that change detection ticks are only
triggered by actual signal changes. Remove the now-unused listenToDom
method from ControlDirectiveHost and its implementation.

(cherry picked from commit 6d36d6c097)
This commit is contained in:
arturovt
2026-10-14 17:48:24 +00:00
committed by Alon Mishne
parent 5761e25356
commit cc515b8b23
5 changed files with 53 additions and 28 deletions
@@ -14,7 +14,7 @@ import type {DirectiveDef} from '../interfaces/definition';
import {InputFlags} from '../interfaces/input_flags';
import {type TNode, TNodeFlags} from '../interfaces/node';
import {isComponentHost} from '../interfaces/type_checks';
import {type LView, RENDERER, type TView} from '../interfaces/view';
import type {LView, TView} from '../interfaces/view';
import {
getCurrentTNode,
getLView,
@@ -25,7 +25,7 @@ import {
import {getNativeByTNode} from '../util/view_utils';
import {debugStringifyTypeForError} from '../util/stringify_utils';
import {listenToDirectiveOutput} from '../view/directive_outputs';
import {listenToDomEvent, wrapListener} from '../view/listeners';
import {wrapListener} from '../view/listeners';
import {setDirectiveInput} from './shared';
import {writeToDirectiveInput} from './write_to_directive_input';
@@ -145,19 +145,6 @@ class ControlDirectiveHostImpl implements ControlDirectiveHost {
);
}
listenToDom(eventName: string, listener: (event: Event) => void): void {
listenToDomEvent(
this.tNode,
this.tView,
this.lView as LView<{} | null>,
undefined,
this.lView[RENDERER],
eventName,
listener,
wrapListener(this.tNode, this.lView, listener),
);
}
setInputOnDirectives(
inputName: string,
value: unknown,
@@ -88,9 +88,4 @@ export interface ControlDirectiveHost<_TPassthroughInput extends string | undefi
value: unknown,
writePredicate?: (currentValue: unknown) => boolean,
): boolean;
/**
* Listens to a DOM event on the host element.
*/
listenToDom(eventName: string, listener: (event: Event) => void): void;
}
@@ -238,7 +238,6 @@
"_platformInjector",
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_stashEventListenerImpl",
"_wasLastNodeCreated",
"activeConsumer",
"addAfterRenderSequencesForView",
@@ -376,7 +375,6 @@
"extractDefListOrFactory",
"extractDirectiveDef",
"finalizeConsumerAfterComputation",
"findExistingListener",
"findMatchingDehydratedView",
"forEachSingleProvider",
"forkInnerZoneWithAngularBehavior",
@@ -509,7 +507,6 @@
"invokeDirectivesHostBindings",
"invokeHostBindingsInCreationMode",
"isAngularZoneProperty",
"isAnimationEventType",
"isAnimationProp",
"isApplicationBootstrapConfig",
"isComponentDef",
@@ -518,7 +515,6 @@
"isCurrentTNodeParent",
"isDestroyed",
"isDetachedByI18n",
"isDirectiveHost",
"isEnvironmentProviders",
"isErrorLike",
"isExistingProvider",
@@ -553,7 +549,6 @@
"leavingNodes",
"linkTNodeInTView",
"listenToDirectiveOutput",
"listenToDomEvent",
"listenToOutput",
"locateDirectiveOrProvider",
"locateHostElement",
@@ -684,7 +679,6 @@
"shouldSearchParent",
"signalSetFn",
"signalValueChanged",
"stashEventListenerImpl",
"storeLViewOnDestroy",
"storeListenerCleanup",
"stringifyCSSSelector",
@@ -60,9 +60,20 @@ export function nativeControlCreate(
bindings['controlValue'] = value;
setNativeControlValue(input, value);
};
// Use `addEventListener` so we only trigger ticks on signal changes.
// See https://github.com/angular/angular/issues/61839.
const nativeEl = host.nativeElement;
// Pass undefined as the raw value since the parse function doesn't care about it.
host.listenToDom('input', () => parser.setRawValue(undefined));
host.listenToDom('blur', () => parent.state().markAsTouched());
const onInput = () => parser.setRawValue(undefined);
nativeEl.addEventListener('input', onInput);
const onBlur = () => parent.state().markAsTouched();
nativeEl.addEventListener('blur', onBlur);
parent.destroyRef.onDestroy(() => {
nativeEl.removeEventListener('input', onInput);
nativeEl.removeEventListener('blur', onBlur);
});
// TODO: move extraction to first update pass?
if (isInput(input) && inputRequiresValidityTracking(input)) {
@@ -25,12 +25,14 @@ import {
numberAttribute,
output,
Output,
provideZonelessChangeDetection,
resource,
signal,
viewChild,
viewChildren,
ViewContainerRef,
ViewEncapsulation,
ɵChangeDetectionScheduler,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
@@ -5185,6 +5187,42 @@ describe('field directive', () => {
expect(field().touched()).toBe(true);
});
it('should not notify the change detection scheduler on blur when control is already touched', () => {
// provideZonelessChangeDetection is required so that ChangeDetectionScheduler is
// wired into the LView environment. In zone mode the scheduler slot is null and
// markViewDirty never calls notify(), making the test meaningless without it.
TestBed.configureTestingModule({providers: [provideZonelessChangeDetection()]});
@Component({
imports: [FormField],
template: `<input [formField]="f" />`,
})
class TestCmp {
f = form(signal(''));
}
const fixture = act(() => TestBed.createComponent(TestCmp));
const inputEl = fixture.nativeElement.firstChild as HTMLInputElement;
const field = fixture.componentInstance.f;
// Put the control into the already-touched state so the next blur is a no-op.
act(() => field().markAsTouched());
expect(field().touched()).toBe(true);
const scheduler = TestBed.inject(ɵChangeDetectionScheduler);
const notifySpy = spyOn(scheduler, 'notify');
// Blur when already touched — nothing changed, so CD must not be scheduled.
//
// Regression: when the blur listener was registered via host.listenToDom('blur', ...),
// wrapListener called markViewDirty unconditionally before running the callback, which
// called scheduler.notify(NotificationSource.Listener) even when selfTouched was
// already true and the signal write was a no-op.
inputEl.dispatchEvent(new Event('blur'));
expect(notifySpy).not.toHaveBeenCalled();
});
it('should synchronize with custom control touched status', () => {
@Component({
selector: 'my-input',