204 Commits

Author SHA1 Message Date
Doug Parker 8ca879e2d8 refactor(forms): expose consequentialHint annotation
Unlike `readOnlyHint` and `untrustedContentHint`, Angular cannot infer any reasonable default value for `consequentialHint` and simply exposes it to users to specify as appropriate.

See: https://groups.google.com/a/chromium.org/g/chrome-ai-dev-preview/c/uHu5kfclbKw/m/dgorjfHPDgAJ
2026-09-10 09:50:14 -07:00
Andrew Scott caeab598c9 refactor(compiler): emit any as type argument for ɵɵInjectableDeclaration
The static `ɵprov` field emitted on `@Injectable()` classes uses `ɵɵInjectableDeclaration<T>`.
When a subclass extends a generic `@Injectable()` base class with contravariant parameters
(such as callback/transformer methods depending on generic type parameters), TypeScript's
static side inheritance check (`typeof Sub extends typeof Super`) fails with `TS2417` because
`ɵɵInjectableDeclaration<Sub>` is not assignable to `ɵɵInjectableDeclaration<Super<any>>`.

Using `any` (`o.DYNAMIC_TYPE`) in `createInjectableType` avoids strict variance checks on
static inheritance for internal Ivy definitions and aligns with other Ivy declaration types.
2026-09-04 07:05:23 -07:00
arturovt 38d093232c fix(forms): warn in dev mode when ngModel cannot reach parent NgForm across component boundary
NgModel injects ControlContainer with @Host(), which stops the injector at
the component host element boundary. When NgForm lives in a parent component
and ngModel lives in a child component, the injection returns null silently
and the control acts standalone — never registering with the form.

To surface this invisible failure, emit a dev-mode warning (NG01354) when
ngModel's @Host() injection finds nothing but the element Injector can still
reach a ControlContainer further up the hierarchy. The warning identifies the
cross-boundary issue and points developers to the viewProviders fix or the
standalone option.

Adds the NG01354 reference page explaining why the warning fires and providing
two remediation paths: bridging ControlContainer via viewProviders, or opting
out with [ngModelOptions]="{standalone: true}".

Fixes #47580
2026-08-17 13:59:40 -07:00
Kristiyan Kostadinov 2a141847a5 fix(forms): add utility to assert that value is a field tree
Adds the `isFieldTree` utility that allows users to assert whether a value is a field tree. This is something that has come up on Material recently and will be useful for users as well.

Fixes #69984.
2026-07-29 08:53:24 -07:00
brysonbw d5e8b1ef7a feat(forms): allow permanent hidden fields in signal forms
Allow the hidden utility function to be called without a configuration object to make fields permanently hidden.
2026-07-29 08:39:39 -07:00
Matthieu Riegler d93e922517 docs(forms): add jsdoc for ReadonlyFieldState 2026-07-08 10:45:31 -07:00
Matthieu Riegler 63c7ac325d refactor(forms): widen AsyncValidatorOptions.factory
This is to accept `Resource` and not only `ResourceRef`.

fixes #69443
2026-06-24 13:03:36 -04:00
cexbrayat 45e8fb5d6c refactor(forms): type built-in getError results
Add overloads for built-in validation error keys so callers get precise error payload types from getError.

This enables signal forms template patterns like:

```html
@if (login.getError('minLength'); as minLengthError) {
  <div>Login should be {{ minLengthError.minLength }} characters</div>
}
```
2026-05-29 14:58:40 +02:00
Douglas Parker 1963a0eb18 refactor(forms): add provideExperimentalWebMcpForms
This enables the use of the `experimentalWebMcpTool` option on signal forms and implicitly declares a WebMCP tool based on the form data model. This is an experiment inspirted by the WebMCP declarative forms API to see if Angular's framework-level knowledge of the form's declarative data model can produce higher quality WebMCP tools than the web standard can on its own with less effort from the developer.

Example:

```typescript
// main.ts

import {bootstrapApplication} from '@angular/platform-browser';
import {provideExperimentalWebMcpForms} from '@angular/forms';
import {MyComp} from './form';

bootstrapApplication(MyComp, {
  providers: [
    // Activate the feature.
    provideExperimentalWebMcpForms(),
  ],
});
```

```typescript
// form.ts

import {Component, signal} from '@angular/core';
import {form} from '@angular/forms';

@Component({ /* ... */ })
export class MyComp {
  private readonly f = form(signal({
    firstName: '',
    lastName: '',
  }), {
    // Implicitly creates a WebMCP tool named `createUser` which accepts a `firstName` and `lastName` as parameters.
    experimentalWebMcpTool: {
      name: 'createUser',
      description: 'Creates a user with the given name.',
    },

    // Invokes the submit action when the agent calls the WebMCP tool.
    submission: {
      action: () => {
        console.log('User clicked submit, or agent called the tool!');
      },
    },
  });

  // ...
}
```
2026-05-15 11:35:22 -07:00
kirjs f9e2b8d902 refactor(forms): update API golden files for signal forms overloads
Regenerated public API golden files after adding overloads for hidden, disabled, and readonly.
2026-05-06 14:10:12 -07:00
kirjs 3f3b85ca44 refactor(forms): regenerate API golden files for signal forms
Regenerated public API golden files after updating rules and validators to use 'when' parameter.
2026-05-06 14:10:12 -07:00
Leon Senft 276c917b34 refactor(forms): add validation rules for date constraints (#68001)
- Added `minDate()` and `maxDate()` for validating constraints on `Date` inputs.
- `ReadonlyFieldState.min` and `.max` now return
  `Signal<NonNullable<TValue>`. This ensures that `min` and `max` inputs
  on custom controls can accept a reliable type (matching their value
  type).
- Made the `TWrite` type parameter of `MetadataKey` contravariant to
  properly indicate that it's writable.
- Added `LimitKey` as a convenience type for defining validation limit
  metadata (e.g. `MAX_NUMBER`, `MIN_DATE`).
- Added `LimitSelectionKey` which can be used to bind a `LimitKey` with
  value-specific aggregation logic, to a generic metadata key (e.g. use
  `MAX_NUMBER` to aggregate numbers for `MAX`).

PR Close #68001
2026-05-06 11:59:18 -07:00
Leon Senft 592a12d6c9 refactor(forms): remove string support from min and max validation rules (#68001)
The `min` and `max` validation rules previously handled `string` values
to accommodate numbers bound to text inputs. However, this is no longer
necessary as the control binding itself handles the conversion.

This change removes string support from these rules, simplifying the
types to `number | null`. The validation logic has been updated to use
concrete checks (`value === null || Number.isNaN(value)`) to ensure safe
TypeScript narrowing.

Associated tests have been updated to:
- Remove string-specific validation checks.
- Add coverage for text input bindings.
- Add coverage for empty input handling (standard behavior where empty
  sets model to null and skips validation).

BREAKING CHANGE: `min` and `max` validation rules no longer support
string values. Bound values must be numbers or null.

PR Close #68001
2026-05-06 11:59:18 -07:00
Alex Rickabaugh 849dba6c65 fix(forms): implement custom control reset propagation
Introduce a highly decoupled FVC and CVA custom control reset mechanism, and implement the framework-wide automatic `transformedValue` and native controls clearing bridge for both new Signal Forms and legacy forms (Template-driven and Reactive).

1. Custom Control Reset Propagation (Bug #2):
- Establish agnostic custom control resetting via `FormFieldBindingOptions.reset` in `FormField`.
- Ensure that `FieldNode.reset()` unconditionally triggers `writeValue` updates on CVA custom controls.
- Protect against duplicate writes during subsequent change detection updates in `control_cva.ts` by verifying and tracking previous written values in the local bindings cache.

2. Unified Framework-wide FormControl Integration:
- Introduce a monorepo-wide private InjectionToken `ɵFORM_CONTROL_INTEGRATION` and `ɵFormControlIntegration` interface to act as the single, decoupled bridge for hooking up FVC parse errors and receiving control resets across both Signal and legacy forms architectures.
- Simplify Signal Forms: make `FormField` implements `ɵFormControlIntegration` directly, removing the intermediate context object and reducing DI boilerplate down to a clean `useExisting: FormField` provider. Triggers the `onReset` callback directly inside `FormField.reset()`.
- Upgrade Legacy Forms: `NG_CONTROL_INTEGRATION_PROVIDER` provides the renamed token. `NgControl` handles the event subscription internally (`set onReset(callback)`) to recursively listen to `control.events` (`FormResetEvent`) lazily only when assigned, resolving all `FormControl` swapping timing and lifecycle cleanup races automatically.

3. Automatic `transformedValue` and Native Controls Utility Clearing:
- Make `Parser.reset()` method required in the interface for a cleaner and non-defensive execution.
- Wire `transformedValue` into the new integration token `ɵFORM_CONTROL_INTEGRATION` to clear validation parsing states on resets.
- Lazily resets the UI-facing `rawValue` linked signal utilizing the original native `linkedSignal.set` callback (`originalSet`), correctly bypassing the UI-to-model parser loopback and preventing redundant model writes during `reset()`.
- Wire up Native Controls (`control_native.ts\Device`): Hook `parent.onReset` inside native element creation to automatically trigger the native `parser.reset()` and force DOM writes (`setNativeControlValue`) back down to the DOM input value during resets, ensuring native elements with pending parsing validation errors are successfully cleared and synced on form resets.

TAG=agy
CONV=8b4cee1e-2117-42a4-b242-c8ec7bf01752
2026-05-06 10:45:40 -07:00
Alex Rickabaugh f9f24fc669 feat(forms): shim legacy NG_VALIDATORS into parseErrors for CVA mode (#67943)
- Injected `NG_VALIDATORS` into `FormField` and exposed it via an internal getter.
- Created a `computed` signal in `cvaControlCreate` to run legacy validators and map into standard validation errors without generic `as any` type assertions.
- Intercepted `registerOnValidatorChange` to trigger updates even when the model value remains unchanged (e.g., going from `null` to `null`).
- Added integration tests to verify parse error propagation and reactivity.

PR Close #67943
2026-04-14 18:32:24 +03:00
arturovt 030422850b docs: add documentation for NG1002
Adds a documentation page for the NG01002 runtime error thrown by
FormGroup and FormArray when setValue is called with a value that is
missing an entry for one or more registered controls.

The error code is also changed from positive (1002) to negative (-1002)
so that Angular appends a link to the error reference page in dev mode,
consistent with how other documented errors (e.g. NG01101, NG01203) are
handled.
2026-04-10 10:54:41 +03:00
Alex Rickabaugh 24e52d450d feat(forms): add debounce option to validateAsync and validateHttp
This adds support for a `debounce` option to the `validateAsync` and `validateHttp` functions.
This allows developers to debounce the triggering of async validators to improve performance.

A `DebounceTimer` type was also added to `@angular/core` to represent the wait condition parameters uniformly.
2026-03-25 14:17:52 -07:00
Alex Rickabaugh 709f5a390c feat(forms): add FieldState.getError()
Added a `getError(kind: string)` method to `FieldState` that returns the first validation error of a given kind, or `undefined` if no such error exists. This method is reactive and will re-evaluate when errors change.

Fixes #63905

Also updated public API goldens and added unit tests.
2026-03-24 15:07:55 -07:00
Alex Rickabaugh ee8d2098cb fix(forms): change FieldState optional properties to non-optional | undefined
This improves compatibility with TypeScript's exactOptionalPropertyTypes.

Fixes #67246
2026-03-24 14:51:31 -07:00
Alex Rickabaugh 74f76d8075 feat(forms): add reloadValidation to Signal Forms to manually trigger async validation
This commit introduces a formal mechanism to manually re-trigger
asynchronous validations in Signal Forms, addressing #66994.

It exposes a `reloadValidation` method on the `FieldState` interface
that recursively cascades down the form tree and invokes the underlying
`ResourceRef`'s `reload()` method for any metadata keys tagged with the
internal `IS_ASYNC_VALIDATION_RESOURCE` symbol.

Fixes #66994
2026-03-19 15:22:13 -07:00
Alex Rickabaugh 83032e3605 fix(forms): support generic unions in signal form schemas
This commit resolves an issue where using an uninstantiated generic type
parameter in a signal form model caused TypeScript compilation failures due to
distributive conditional types (#66596). The previous attempt to fix this issue
by tuple-wrapping everything caused another bug (#65535) that prevented property
access on generic unions.

This commit balances the need to resolve nested generic property access while
handling infinitely recursive generic structures without depth errors.

What changed and why:
- Base State Wrappers: Tuple wrappers (`[TModel] extends [AbstractControl]`) are
  applied to `FieldTreeBase` to safely defer generic evaluation. This prevents
  primitive unions (like `boolean`) from incorrectly evaluating to `never`.
- Naked Map Over Children: Object subfield checks (`TModel extends Record`) are
  re-evaluated as purely naked conditionals. Eager distribution over generics
  allows users to directly access shared properties of unresolved union types.
- Array Interface Deflection: `ReadonlyArrayLike<T>` generic abstraction is
  redefined as an explicit `interface` instead of a mapped `Pick` type alias.
  This optimally intercepts TypeScript from eagerly evaluating infinitely
  recursive array structures (e.g. `RecursiveType = (number | RecursiveType)[]`).
- Overloaded Context Methods: `FieldNodeContext.stateOf` and `fieldTreeOf` are
  defined as explicitly overloaded class methods and lexically bound (`this`) in
  the constructor. These changes are required to safely align the runtime bindings
  with the tautological conditionals implemented in the `RootFieldContext`
  interface structure.

Fixes #65535
2026-03-17 17:59:36 -06:00
Alex Rickabaugh c4ce3f345f feat(forms): template & reactive support for FVC
Implement support for `FormUiComponent`s in both Reactive and Template-driven
forms. This allows components that use the new signal-based form control
architecture to be used seamlessly within existing Angular form paradigms.

Key changes:
- Integrated `ɵngControlCreate` and `ɵngControlUpdate` lifecycle hooks into
  `NgModel`, `FormControlDirective`, and `FormControlName`.
- Implemented branching logic to choose between the traditional `ControlValueAccessor` (CVA) path and the new FVC path based on the host element's capabilities.
- Added comprehensive unit tests for FVC integration in both Reactive (`reactive_fvc.spec.ts`) and Template-driven (`template_fvc.spec.ts`) forms, covering:
    - Value synchronization (model -> view and view -> model).
    - Status synchronization (touched, dirty, valid, invalid, pending, required).
    - Error propagation and `parseErrors` support.
    - Fallback behavior to native DOM properties (disabled, required) when FVC inputs are missing.
    - Graceful fallback to CVA when no FVC pattern is detected.
- Refined `NgModel` to correctly handle `required` validation via its existing `RequiredValidator` directive while supporting FVC for other properties.
2026-03-17 13:18:26 -06:00
Alex Rickabaugh b2f08574e8 refactor(forms): base implementation of custom control binding in NgControl
Update `NgControl` to support binding to custom controls via the new `ngControlCreate` and
`ngControlUpdate` lifecycle hooks. This will allow Reactive and Template-driven forms to integrate
with components that use the new `FormValueControl` (FVC) binding convention.

Key changes:
- Implement synchronization of control state between `FormControl` and custom controls.
- Add support for `parseErrors` signals from custom controls, integrating them into the Reactive
  Forms validation loop via a dynamic validator.
- Convert Reactive Forms errors into `ReactiveValidationError` objects for consumption by custom
  controls.
- Update `NgModel`, `FormControlDirective`, and `FormControlName` to provide necessary dependencies
  (`Injector`, `Renderer2`) to `NgControl`.
- Rename `setUpControl` to `setUpControlValueAccessor` to clarify its role in the traditional
  CVA path.
2026-03-17 13:18:26 -06:00
Alex Rickabaugh 723abd4d57 refactor(forms): move valueAccessor selection out of ctor
Delay the selection of a CVA until after the `ɵɵcontrol` instruction has a chance to execute.
This is necessary to delay the error that would be thrown for a missing CVA until after we have a
chance to recognize we're actually on an FVC/FCC.
2026-03-17 13:18:26 -06:00
Alex Rickabaugh 3983080236 feat(forms): support ngNoCva as an opt-out for ControlValueAccessors
If `FormsModule` or `ReactiveFormsModule` is present in the scope of a
template, plain `<input>` and other form elements will get default CVA
directives added. This commit adds an `ngNoCva` attribute as a negative
selector for those directives, so `<input ngNoCva>` elements will not have
them matched.
2026-03-17 13:18:26 -06:00
Leon Senft eeba51c50b refactor(forms): make markAsTouched() touch all descendants by default
`markAsTouched()` now marks all descendants as touched. In general this
method is called when controls update the model. Most controls update
leaf nodes, in which case this change has no effect.

Marking all descendants allows triggering validation for subsections of
a form, independently from having to call `submit()` on the entire form.

`markAsTouched()` now accepts a `MarkAsTouchedOptions` parameter, which
includes a `skipDescendants` property. This can be used mark only the
receiving field as touched: `node.markAsTouched({skipDescendants: true})`.
2026-03-16 16:03:36 -06:00
kirjs b061495134 refactor(forms): Add more tests
thoroughly tests both propagation directions
2026-03-16 15:24:20 -06:00
kirjs 6703e6c803 refactor(forms): add structured extract filter
It's a helper function that takes a form, and extrasts it's value unwrapping compat values and also allowing to filter them.
2026-03-16 15:24:20 -06:00
Matthieu Riegler 4874c54c08 refactor(forms): remove deprecated WithField
This commit removes, `WithField`, `WithOptionalField`, `WithoutField`
2026-03-12 14:55:46 -06:00
Leon Senft 3e7ce0dafc fix(forms): restrict SignalFormsConfig to a readonly API
Introduce `FormFieldBinding` to represent a binding between a field and
a UI control through a `FormField` directive. This interface is used to
restrict `SignalFormsConfig` and `formFieldBindings` to a readonly API.

Fix #65779.
2026-03-10 15:07:42 -07:00
Leon Senft a1a6c5282e refactor(forms): restrict reactive logic to a readonly API
Reactive logic in forms is not intended to mutate state, but this was
poorly communicated by the permissive and highly mutable field context
provided to all logic functions. This change splits all of the
state-related API into writable and readonly interfaces.

* Top-level functions that produce a `FieldTree` (e.g. `form()`) expose
  writable signals (e.g. `value: WritableSignal<T>`) and mutating
  methods (e.g. `markAsDirty()`).

* Reactive logic expose readonly signals (e.g. `value: Signal<T>`) and
  omit mutating methods.
2026-03-10 15:07:42 -07:00
Leon Senft c767d678cf feat(forms): add 'blur' option to debounce rule
Expands the `debounce` rule configuration to accept `'blur'`. When this option
is provided, the rule will delay model synchronization until the field loses
focus (is touched). This introduces a debouncer that defers resolution
until the framework automatically aborts pending debounces upon touch events.
2026-03-05 09:55:14 -08:00
Angular Robot 0af53fbb12 build: update cross-repo angular dependencies
See associated pull request for more information.

Closes #67274 as a pr takeover
2026-02-25 10:17:51 -08:00
Miles Malerba 23fd8fa586 fix(forms): use consistent error format returned from parse
Aligns the errors returned from the `parse` function in
`transformedValue` to use the same convention as the rest of signal
forms (a property called `error` that can contain a single error or list
of errors)
2026-02-23 09:11:51 -08:00
Leon Senft fb166772d2 fix(forms): split the touched model into an input and touch output
The `touched` property was never meant to support two-way binding; a
control should not be able to dictate that a field is no longer touched.

* The `touched` input represents the touched state of the field.
* The `touch` output allows a control implementation to indicate when
  the bound field is touched.

Note the distinction is that the `touch` output indicates _when_ the
field is touched, and not _whether_ the field is touched.
2026-02-19 09:07:03 -08:00
Leon Senft b481294047 refactor(forms): remove unused generic type parameter
The `TValue` type parameter was unused by `FormUiControl`.
2026-02-17 13:02:42 -08:00
Miles Malerba a6a0347998 refactor(forms): extract common parser logic (#66917)
native controls and custom controls (via transformedValue) use similar
parsing logic but it needs to be hooked up differently. This commit
extracts the common bits into a shared piece.

PR Close #66917
2026-02-13 12:11:06 -08:00
Miles Malerba 22afbb2f36 feat(forms): add parsing support to native inputs (#66917)
Integrates native inputs with the new parseErrors API so that they can
report parse errors when the user types an un-parsable value (e.g. "42e"
in a number field).

When a user types an un-parsable value, the model does not update. It
retains its previous value and a parse error is added for the control
that received the un-parsable value.

PR Close #66917
2026-02-13 12:11:06 -08:00
Leon Senft 3606902b33 refactor(forms): relax [formField] input type from FieldTree to Field
`FieldTree` was an unnecessarily specific type for the `[formField]`
input. It forced the directive to care about what _kind_ of `FieldTree`
was bound–specifically whether it was Reactive Forms compatible or not.
This made it difficult to author forms system-agnostic components with
passthrough `[formField]` inputs.
2026-02-11 11:45:20 -08:00
Miles Malerba ba009b6031 feat(forms): add form directive
Adds a `formRoot` directive to manage submitting the form in signal
forms.
2026-02-10 14:34:48 -08:00
Miles Malerba f56bb07d83 feat(forms): add field param to submit action and onInvalid
The `action` and `onInvalid` handlers now recevie two pieces of
information:
1. The form that is being submitted
2. The specific field that the submit was triggered on

Remove the `submit()` method on field state - supporting this is complex
from a typing perspective, since the `FieldState` only knows its
`TValue` type, not the `TModel` type of its owning `FieldTree`. Rather
than try to pack additional generics on to `FieldState`, we'll just
leave the `submit` function as a standalone importable function.
2026-02-09 14:49:43 -08:00
Leon Senft b772f518f1 refactor(forms): add fieldTree property to FieldState
The `fieldTree` property of `FieldState` returns its associated
`FieldTree`.

Note that the round trip from `FieldTree` to `FieldState` and back will
lose type information. This is because `FieldState` intentionally does
not know whether it came from a pure Signal Forms field tree, or a
Reactive Forms compatible field tree:

```ts
// Pure Signal Forms:
const x: FieldTree<string>;

x();           // FieldState<string>;
x().fieldTree; // FieldTree<unknown>

// Reactive Forms compatibility:
const y: FieldTree<FormControl<string>>;

y();            // FieldState<string>;
y().fieldTree;  // FieldTree<unknown>;
```
2026-02-09 12:28:35 -08:00
Miles Malerba adfb83146b fix(forms): simplify design of parse errors
Reoves the `parseErrors` property on `FormUiControl` and instead
introduces a new utility `transformedValue` that automatically handles
synchronizing the raw value and model value using the given `parse` and
`format` functions. It also automates the reporting of `parseErrors` to
the `FormField`, simplifying the API surface
2026-02-09 12:27:41 -08:00
SkyZeroZx 24c0c5a180 feat(forms): support signal-based schemas in validateStandardSchema
Allow `validateStandardSchema()` to consume a computed schema so
validation rules stay in sync when the schema changes over time.

This supports schemas stored in computed signals (e.g. zod schemas that
depend on input signals) and ensures the effective schema updates after
initialization instead of being captured once.

Fixes #66867
2026-02-06 07:40:46 -08:00
Kristiyan Kostadinov 680d99b1c3 refactor(forms): work around internal issue
Works around an internal property renaming issue by changing how we declare the interface for `InteropNgControl`.
2026-02-04 14:25:44 -08:00
Miles Malerba 95ecce8334 feat(forms): allow setting submit options at form-level
Updates FormOptions to accept a submission configuration object.
This allows defining default submit options (action, validation behavior, etc.)
when creating the form, which can be overridden when calling submit().
2026-02-03 12:43:31 -08:00
Miles Malerba dd208ca259 feat(forms): update submit function to accept options object
Changes the `submit` function signature to accept a `FormSubmitOptions` object instead of a direct action callback.
This allows for more flexibility, including:

- `action`: The standard submit action to perform with the data.
- `onInvalid`: A callback to execute when the submit action is not triggered due to failing validation
- `ignoreValidators`: Controls whether pending validators or invalid validators should be ignored

Also updates the return value of `submit` to a `Promise<boolean` to indicate submission success.
2026-02-03 12:43:31 -08:00
kirjs 80f08838b0 refactor(forms): Address more feedback
Clean up tests, drop old todos
2026-02-02 14:51:40 -08:00
kirjs 05d5087252 refactor(forms): use markAsPristine and markAsUntouched on field node
This make things cleaner
2026-02-02 14:51:40 -08:00
Leon Senft 26d12158e1 refactor(forms): convert FieldState.controlValue to a WritableSignal
Remove `setControlValue()` from `FieldState` and convert `controlValue` to a
`WritableSignal` whose setter implements the debounced syncing behavior
of `setControlValue()`.
2026-01-30 09:14:14 -08:00