angular / angular/components

Easier Cross-field-validation for mat-form-field/mat-error combinations

Open
#18,065 10 comments 14 reactions 0 assignees View on GitHub
area: material/form-field feature needs: discussion P5
Dominant language
TypeScript
Stars
25k
Forks
6.8k
Avg merge
1d 8h
Merged PRs (30d)
91

Description

#### Feature Description

In reactive forms, cross-field validation requires the validation logic to be placed with the parent form instead of the individual control.
The existing feature works fine, however, changing the relevant `mat-form-field`(s) into an error-state to enable showing underlying `mat-error`(s) has to be done by calling the relevant `FormControl`'s `setErrors()` function.

However, with a directive, we need only to perform validation on the parent form and return `ValidationErrors`. The child controls can themselves detect whether they should go into error-state or not, and the developer need not worry further about it.

First, we run a normal validator function on the form that does nothing but return `ValidationErrors`. Then, we pass the key(s) of the error(s) for which we want cross-validation, to the custom directive.
Please note how the `mat-error`'s `*ngIf` depends upon the error-set of the `FormControl`, just like in normal validation, although it would still work if it depended on the error set of the parent `FormGroup` (which is what we do currently).
```

Range Start

Value must be less than End

```

#### Use Case
Developer convenience and ease of use. Brings more consistency between normal validation and cross-validation. Allows child controls to 'inherit' some user-specified errors of the parent on `valueChanges`.

#### StackBlitz
https://stackblitz.com/edit/angular-cross-validation-directive

Contributor guide

Open the contributing guide

Research direction

Start with the linked StackBlitz example and review how the reactive parent form, child FormControls, mat-form-field, and mat-error currently interact. Done means a directive can receive selected parent-form error keys, expose them on the relevant child controls, and let mat-error use the child control's error state without manual setErrors() calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
angular, typescript
Domain
frontend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.