← 输入框|github.com|刷新
Skip to content

fix(forms): preserve intermediate keystrokes in signal formField - #70391

Open
shoemoney wants to merge 1 commit into
angular:mainfrom
shoemoney:fix/formfield-intermediate
Open

shoemoney wants to merge 1 commit into
angular:mainfrom
shoemoney:fix/formfield-intermediate

Conversation

@shoemoney

@shoemoney shoemoney commented Aug 26, 2026 •

Copy link
Copy Markdown

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • angular.dev application / infrastructure changes
  • Other... Please describe:

What is the current behavior?

A native signal FormField writes a parsed user value back to the DOM during the next update. That can discard the spelling being edited or move the caret. For example, Chromium can display 14. while exposing value="14" and badInput=false; writing 14 back loses the dot and disrupts the next digit.

Fixes #69635.

What is the new behavior?

A real input event records its resulting control value. The next directive update skips echoing that value to the DOM and consumes the marker, including when the binding value has not changed. External model changes continue to update every native control immediately. Reset always writes the model value, blur clears the marker, and changes to a radio's value binding still force synchronization.

Validity notifications keep their separate parsing callback. The change adds no document injection, focus checks, deferred writes or intermediate-number parser. Existing Number() parsing, including scientific notation and Infinity for numeric text controls, is preserved.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

The PR is one commit on ef7ae1fc41d885d1c6744ad5ddf472880b930cad. Existing web tests are preserved. The new native_control_edit.spec.ts adds 19 TestBed cases covering the own-edit echo, immediate external updates, numeric spellings, the existing numeric parsing contract, nullable controls, radio bindings, validity notifications and reset. These 19 TestBed cases have not been run.

Validation for b393fb4adb5fcf5766d608acc6e39bc1a009f460:

  • The canonical pnpm ng-dev format files and pnpm ng-dev format changed --check refs/remotes/upstream/main commands pass with the pinned formatter from current main. TypeScript syntax parsing and git diff --check pass.
  • Ten isolated Chrome 158.0.8127.107 proof groups pass using the actual production native-control functions with form-state, parser and validity-scheduling test doubles. They include physical 14. typing in light and shadow DOM, immediate external writes, nullable controls, scientific notation/Infinity, radio changes, validity notifications and reset. Four deliberately broken variants fail the corresponding checks.
  • The requested full target, pnpm bazel test //packages/forms/signals/test/web:test, remains unrun. The remote validation launch was cancelled before commands executed, so the complete TestBed/Bazel validation is still outstanding.

@pullapprove
pullapprove Bot requested a review from kirjs August 26, 2026 00:03
@ngbot ngbot Bot added this to the Backlog milestone Aug 26, 2026
@JeanMeche

Copy link
Copy Markdown
Member

That would be a fix for #69635. Last time we tried to fix it, #69637 was breaking.

@JeanMeche

Copy link
Copy Markdown
Member

I've run the unit tests added in PR #69637 against this branch to check if they all pass. It seems the current fix in this PR does not fully handle all the edge cases covered by those tests.

Specifically, the following 3 tests are failing:

  1. Preserving negative decimals:

    • numeric inputs > parsing logic > should preserve a negative decimal typed into a number input
    • text input with numeric model > should preserve a negative decimal typed into a text input with a numeric model
      Both fail with Expected '0' to be '-0'.. When the user types -0, it is still being normalized/parsed to 0.
  2. Parsing non-decimal numeric text:

    • text input with numeric model > should not parse non-decimal numeric text
      Fails with Expected 5 to be 42.. The test checks inputs like 0b0101 and 0x22, which shouldn't be parsed as decimal numbers (they should result in a parse error), but the current implementation likely uses Number() which incorrectly parses 0b0101 into 5.

For context, PR #69637 resolved these issues by introducing a custom parseDecimalNumber function that strictly handles decimal inputs and preserves intermediate strings correctly. You might need to incorporate a similar strict decimal parsing logic to get these edge cases completely green.

@shoemoney

Copy link
Copy Markdown
Author

Added unit tests and switched to a strict decimal parser (Number and parseFloat must agree) shared between isIntermediate and the text-input numeric read path. This fixes the -0 normalization and stops 0b0101/0x22 from being accepted as numbers. Pushed in e3553b8.

@shoemoney

Copy link
Copy Markdown
Author

Both threads addressed:

Test coverage (@JeanMeche): added packages/forms/signals/test/web/number_input.spec.ts covering preserving -, ., -., trailing .; preserving a typed -0/-0.5 on both a number input and a text input with a numeric model; decimal strings whose numeric value matches controlValue but whose string representation differs (1.0/1.00 vs 1); and rejecting 0b0101/0x22 as parse errors. Switched to a strict decimal parser (Number() and parseFloat() must agree) shared between isIntermediate() and the text-input numeric read path, which is what fixed the three failing cases from #69637.

DOCUMENT injection (@SkyZeroZx): good catch, thanks. Switched to inject(DOCUMENT) from @angular/common — the same pattern InputValidityMonitor already uses in this directory — instead of the global document, and threaded it into nativeControlCreate. That should address the SSR/platform-abstraction concern.

@apimentasoto

Copy link
Copy Markdown

what is holding this up? Can we expect this to be merged any time soon?

Thanks :)

@shoemoney

Copy link
Copy Markdown
Author

The test jobs on this PR are green. The merge status check lists what is left: pullapprove reports 2 pending code reviews, the required target: * label is not set, and the Google internal presubmit has not been started. Those are maintainer actions.

The review feedback is addressed. Unit tests landed in packages/forms/signals/test/web/number_input.spec.ts in e3553b8, and dacd050 switched the focus check to an injected DOCUMENT. The changes-requested review from 2026-08-26 has not been revisited since. I do not have a merge date.

@JeanMeche JeanMeche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENT: Great work on addressing the previous feedback! The use of the injected DOCUMENT and the added tests look good.

However, I noticed a critical edge case that this fix doesn't fully solve for <input type="number"> on Chromium-based browsers (Chrome/Edge). I've left a few inline suggestions below to address this and to consider scientific notation for text inputs.

@shoemoney

Copy link
Copy Markdown
Author

Thanks for the detailed review. Addressed in 0679492, pushed to this branch.

  1. Comment on why formatting is skipped only under those conditions, and why focus matters (packages/forms/signals/src/directive/control_native.ts, line ~124): expanded the comment above the guard. Focus is the signal that this specific control is the one being actively edited right now, so its raw text should win over the model until blur; any other control bound to the same field is not being edited and must keep reflecting the model as it changes.

  2. badInput on Chromium number inputs (line ~128): implemented as suggested. InputValidityMonitor already exposes isBadInput (it is used the same way in native.ts's getNativeControlValue), so no new accessor was needed. Wired validityMonitor.isBadInput(input) into the write-back guard alongside isIntermediate, gated on focus the same way. Added a regression test with two inputs bound to the same field: input1 gets badInput with an empty value while focused, input2 pushes a new value to the shared model, and the test confirms input1's display is not clobbered while badInput is set, then confirms it resumes syncing once badInput clears.

  3. Scientific notation and a leading plus for input type="text" inputmode="decimal" (line ~137): left the code unchanged. parseDecimalNumber already accepts complete literals like "1e2" and "+1" (Number and parseFloat agree on both), so once one of those is fully typed it is preserved by the existing "parses to the same value but the string differs" branch of isIntermediate, the same mechanism that already preserves "-0" and "1.0". An incomplete literal such as "1e", "1e-", or a lone "+" fails to parse, and createParser only calls setValue on a successful parse, so the control value never changes and this directive never attempts a write-back over that raw text in the first place. Added two tests that type through both sequences end to end and assert the input's value at each step, to document this and guard against a regression, rather than adding new whitelist logic for a case that is not actually being erased.

Ran the zoneless_web_test_suite target for packages/forms/signals/test/web (Chromium and Firefox), prettier --check, and tslint on the touched files; all pass.

Not changed: no new accessor on InputValidityMonitor (isBadInput already existed), and no changes to parseDecimalNumber or isIntermediate's whitelist for point 3, for the reason above.

@shoemoney

Copy link
Copy Markdown
Author

Follow-up in b4094a1: a model write deferred while the number input has badInput is now applied on blur. A later user edit or reset cancels that pending write, and blur reads the current field binding.

In the September 18 local verification, the regression failed before the fix in both browsers. After the fix, the full signals web suite passed: Chromium 360; Firefox 356 with 4 skips. Formatting and project-aware lint passed. Native Chrome typing also verified blur synchronization, newer valid/invalid edits, reset, and rebinding.

@shoemoney
shoemoney force-pushed the fix/formfield-intermediate branch from d1bcbbe to b035e76 Compare September 25, 2026 20:23
@shoemoney

Copy link
Copy Markdown
Author

Removed a duplicate fixup! prefix in b035e76. All 11 commits remain, with identical file trees; source and tests are unchanged. The repository's commit-range validator now passes locally.

The six non-lint CI jobs passed on d1bcbbe. CI for the new head is pending.

@shoemoney

Copy link
Copy Markdown
Author

The adev job failed the NodeRuntimeSandbox out-of-memory test on all three attempts. It expected one call to decreaseInstancesCounter and got two. The other six PR jobs passed.

The sandbox, spec, alert manager and BUILD files are identical at CI base edca4f0 and tested merge 4c99fa7. The assertion and counter logic came from upstream commit 7dcedd4. The base's adev job was canceled, so I have not confirmed the failure on a clean base or ruled out an indirect interaction with this PR.

@JeanMeche
JeanMeche removed the request for review from kirjs September 30, 2026 11:31
@cursor
cursor Bot force-pushed the fix/formfield-intermediate branch from 9b3f80a to b263638 Compare October 25, 2026 20:33

@JeanMeche JeanMeche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENT: Thanks for the updates @shoemoney! Extracting parseDecimalNumber and tracking lastEditedValue / hasPendingValueWrite cleaned up a lot of the previous issues. Taking a closer look at isIntermediate and hasPendingValueWrite, there are still a few edge cases and simplifications worth addressing.

@shoemoney

Copy link
Copy Markdown
Author

Addressed in 10bcf30.

Write-back / hasPendingValueWrite: the focused path now always assigns with Object.is, so a later external update that restores lastEditedValue clears a stale deferral, and -0 stays distinct from +0.

isIntermediate: dropped endsWith('.') and EXPONENT_PREFIX_REGEXP. A value is intermediate only for a number or null model, and only when the text is one of +, -, ., -., +. or a decimal spelling that is not the canonical String form (-0, 1.0, +1). Non-numeric text like hello. / ten. now takes external updates immediately while focused.

Tests: those two strings expect an immediate update; ['-0', '1.0', '+1', '+.'] stay on screen until blur. Added coverage for restoring the last edited value, and for deferring +0 while the field shows -0.

//packages/forms/signals/test/web:test passed on Chromium and Firefox; prettier and tslint passed on the touched files.

@JeanMeche

Copy link
Copy Markdown
Member

Can you please squash everything and drop the co-author. We cannot proceed with a PR that fails the CLA check. Thank yuo.

@shoemoney
shoemoney force-pushed the fix/formfield-intermediate branch from 10bcf30 to 91a9b57 Compare November 11, 2026 22:10
@shoemoney
shoemoney force-pushed the fix/formfield-intermediate branch from 91a9b57 to 13de728 Compare November 28, 2026 20:02
@shoemoney

Copy link
Copy Markdown
Author

Thanks for the review and for spelling out the CLA blocker. I rebased onto current main and pushed 13de728 as a single commit authored and committed solely by me, with no co-author trailer. cla/google is green on that head.

The inline fixes and regression tests are included, and I resolved the addressed threads. The Signal Forms browser target passes in Chromium and Firefox; formatting, targeted lint, and commit-message validation also pass. This is ready for another review. The workflow approvals, internal presubmit, and target label still need maintainer action.

@karptonite

karptonite commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

A case this doesn't cover yet, in Chrome (158.0.8127.37) on 22.1.5 (the write-back is unchanged in 22.3.0):

<input type="number" [formField]="f"> with a number | null model. Type 14.3, then Backspace. The input shows 14., but Chrome reports input.value === '14' with validity.badInput === false. The model changes from 14.3 to 14, the binding writes valueAsNumber = 14, the text becomes 14, and the caret moves to the start, so the next digit lands in front (914). A plain <input type="number"> in the same page keeps 14. and the caret.

With this PR, isBadInput is false and isIntermediate('14', 14) is false ('14' === String(14)), so the write still happens. The number-input tests drive setInputState, which can't represent Chrome showing 14. while reporting 14.

Since the input listener already records lastEditedValue, one option: while focused, skip the write whenever Object.is(controlValue, lastEditedValue). That is the user's own edit, already on screen, and it doesn't depend on what the browser exposes about unfinished text.

(This comment was prepared with Claude, but we are running into this issue on production.)

@shoemoney

Copy link
Copy Markdown
Author

Thanks for the precise Chrome reproduction, @karptonite. Fixed in 32e79a7: a focused number input avoids echoing its own edit, and real model writes/reset/blur clear that edit marker so later external updates still apply.

I reproduced the 14. to 914 sequence on Chrome 158.0.8127.88. Eight isolated browser cases using the production native-control functions with form-state/parser test doubles pass; negative controls catch the original failure and stale edit tracking. Two async web regressions are included. The full Bazel web target remains unrun locally.

@karptonite

Copy link
Copy Markdown
Contributor

Thanks, @shoemoney, I really appreciate it! I hope this is merged soon--I don't know how the process for PRs generally works on Angular, but this seems like a really worthwhile bug fix!

@shoemoney

Copy link
Copy Markdown
Author

Thanks, @karptonite! Your reproduction helped catch the remaining caret issue. I hope it lands soon too. The timing is up to the Angular maintainers; I’ll keep an eye on the PR and address any further feedback.

@JeanMeche JeanMeche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENT: Stepping back and looking at the current implementation, there is a broader design question worth considering alongside a few concrete edge cases noted inline.

Should external model updates be deferred at all?

This PR has accumulated three mutable state flags (hasPendingValueWrite, lastEditedValue, hasUserEdit), isIntermediate(), isBadInput, and a blur-flush path because it mixes two distinct concerns:

  1. Avoiding echoing the user's own edit back to the same element (the root cause of #69635, and why 32e79a7 still had to add input.type === 'number' && isUserEdit for Chrome displaying 14. while reporting "14" without badInput).
  2. Deferring external model writes until blur while a focused input holds an intermediate spelling or badInput.

Deferring external updates creates inconsistent behavior: a programmatic model write (e.g. a keyboard shortcut, "Reset"/"Max" action that doesn't steal focus, or linked field update) applies immediately if the focused input currently shows 14, but is silently deferred until blur if it shows 14.0, -0, or -. Every other Angular form control applies external model writes immediately even while focused.

If we instead only skip echoing the user's own edit back to the DOM (and clear edit tracking once consumed / on blur / on reset), 14., 1.0, -0, -, and 1e are all preserved during typing without needing isIntermediate(), hasPendingValueWrite, deferred blur flushes, or rejecting scientific notation in parseDecimalNumber, while external updates stay consistent and immediate.

Other notes

  • Please see the inline comments on isIntermediate (leaking into non-numeric controls and string | null), watchValidity (dropping hasPendingValueWrite on non-user validity changes), parseDecimalNumber (accepting Infinity/-Infinity/+Infinity and breaking 1e5 on text inputs), and inject(DOCUMENT) overhead.
  • Before merging, please also squash the two commits into one and make sure the full //packages/forms/signals/test/web:test suite passes on the latest head.

@shoemoney
shoemoney force-pushed the fix/formfield-intermediate branch from 32e79a7 to b393fb4 Compare December 1, 2026 23:07
@shoemoney

Copy link
Copy Markdown
Author

Thanks @JeanMeche for the concrete external-write and validity-notification examples. I replaced the deferral logic with a marker for a real input event's own echo, consumed on every update. External model writes now update immediately; validity notifications use their original callback. The document injection and parser helper are gone, so scientific notation and the existing Infinity behavior are preserved.

I squashed the PR to one commit, b393fb4, on current main. The canonical formatter passes. Ten Chrome proof groups using the production native-control functions pass, and four deliberately broken variants fail. That proof uses form-state/parser/validity-scheduling doubles; it does not run Angular TestBed.

I added 19 focused TestBed cases, including a setter assertion distinguishing validity notifications from user input. Those cases and the full //packages/forms/signals/test/web:test target remain unrun: the dev2 validation launch was cancelled before any commands ran. The requested full-suite validation is still outstanding. I have updated the description to make that boundary explicit.

Skip the native value write for the control value produced by a user input event, then consume the marker on every update. Keep external writes immediate and preserve existing parsing semantics.

Cover native edits, resets, validity notifications and supported nullable numeric and string clearing models.
@shoemoney
shoemoney force-pushed the fix/formfield-intermediate branch from b393fb4 to 59f1b50 Compare December 2, 2026 06:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

forms: signals - number [formField] loses characters while typing (parsed value written back to the input on every keystroke)

5 participants