In Angular Material 22, how do you make a composite bank-account control, with routing and account number inputs, work inside mat-form-field as a MatFormFieldControl?
answer
- the wrapper reads a contract
- provide the token, use the existing instance
- state as booleans or signals
- describedby ids and container clicks
- reuse the app's error matcher
basics
~10 sImplement the MatFormFieldControl contract: provide MatFormFieldControl with useExisting, expose id, ngControl, focused, empty, shouldLabelFloat, required, disabled and errorState, and implement setDescribedByIds and onContainerClick. In v22 state may be signals, making stateChanges optional.
solid answer
~40 s`mat-form-field` only talks to a child that provides `MatFormFieldControl`, so the bank-account component adds `providers: [{provide: MatFormFieldControl, useExisting: BankAccountInput}]` and implements the contract. In Angular Material 22 that is an abstract directive class: `id` (bound to the host), `ngControl` (or `ngField` for Signal Forms), and `focused`, `empty`, `shouldLabelFloat`, `required`, `disabled` and `errorState`, each a `boolean` or a `Signal<boolean>`. Two methods are abstract: `setDescribedByIds(ids)` must put the hint and error ids on the group's `aria-describedby`, and `onContainerClick()` focuses the right inner input. `stateChanges` is now optional: the form field reads signal members directly, so you emit only for plain properties. For `errorState`, inject `ErrorStateMatcher` so the control follows the same timing as `matInput`. The value plumbing is Angular's `ControlValueAccessor`; set `ngControl.valueAccessor = this` instead of providing `NG_VALUE_ACCESSOR`.
code
ts · 31 lines@Component({
selector: 'app-bank-account-input',
templateUrl: './bank-account-input.html',
providers: [{provide: MatFormFieldControl, useExisting: BankAccountInput}],
host: {'[id]': 'id', '(focusin)': 'focused.set(true)', '(focusout)': 'onFocusOut($event)'},
})
export class BankAccountInput implements MatFormFieldControl<BankAccount>, ControlValueAccessor, DoCheck {
private static nextId = 0;
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly matcher = inject(ErrorStateMatcher);
private readonly parentForm = inject(FormGroupDirective, {optional: true});
protected readonly formField = inject(MAT_FORM_FIELD, {optional: true});
readonly ngControl = inject(NgControl, {optional: true, self: true});
readonly id = `bank-account-${BankAccountInput.nextId++}`;
readonly controlType = 'bank-account';
readonly parts = signal({routing: '', account: ''});
readonly focused = signal(false);
readonly empty = computed(() => !this.parts().routing && !this.parts().account);
readonly shouldLabelFloat = computed(() => this.focused() || !this.empty());
readonly required = input(false, {transform: booleanAttribute});
readonly disabled = signal(false);
readonly stateChanges = new Subject<void>();
errorState = false;
ngDoCheck() {
const next = this.matcher.isErrorState(this.ngControl?.control ?? null, this.parentForm);
if (next !== this.errorState) {
this.errorState = next;
this.stateChanges.next();
}
}go deeper
Know that mat-form-field only accepts children that provide MatFormFieldControl, and that matInput and mat-select are the built-in ones.
Walk through the members a control exposes and what the field does with each: label targeting, floating, focus styling, required marker and error switching.
Build the composite control end to end: useExisting provider, signal state, matcher-driven errorState, describedby and labelledby wiring, and the valueAccessor assignment that avoids the cycle.
Decide when a composite control earns a MatFormFieldControl implementation versus two plain fields, given the accessibility and maintenance cost across a shared form library.
## What `mat-form-field` needs from a control `<mat-form-field>` draws the label, container, hints and errors, but it knows nothing about inputs. It injects one **`MatFormFieldControl`** from its content and reads that object's state to decide whether the label floats, whether the field looks focused, disabled or invalid, which element the label points to, and where clicks on the container go. `matInput`, `mat-select` and the chip grid all provide it; a composite component must provide it too, or the field throws `mat-form-field must contain a MatFormFieldControl`. On an insurance claim intake form, the payout account is a **bank-account control**: one component with two inputs, a nine-digit routing number and an account number, whose value is `{routing, account}`. Placed in a `<mat-form-field>`, it should float a "Payout bank account" label, show a hint and errors, and look focused while either inner input has focus. ## The v22 contract In Angular Material 22, `MatFormFieldControl<T>` is an abstract class decorated with `@Directive()`. Its members: | Member | Type | What the form field does with it | |---|---|---| | `id` | `string` | Points the `<mat-label>`'s `for` at it (unless `disableAutomaticLabeling`) | | `ngControl` / `ngField` | form directive or Signal Forms field | Mirrors validity and touched state as classes on the field | | `focused` | `boolean \| Signal<boolean>` | Focused styling and the active indicator | | `empty` | `boolean \| Signal<boolean>` | Label position when not focused | | `shouldLabelFloat` | `boolean \| Signal<boolean>` | Floats the label | | `required` | `boolean \| Signal<boolean>` | Shows the required marker on the label | | `disabled` | `boolean \| Signal<boolean>` | Disabled styling | | `errorState` | `boolean \| Signal<boolean>` | Switches the subscript from hints to errors | | `controlType` | optional `string` | Adds `mat-form-field-type-<controlType>` to the field | | `stateChanges` | optional `Observable<void>` | Tells the form field to re-check plain properties | | `setDescribedByIds(ids)` | abstract method | Hands over the ids of the visible hints and errors | | `onContainerClick(event)` | abstract method | Called when the user clicks the field's container | Older majors described an interface with a required `placeholder` and a mandatory `stateChanges` subject. In v22 `placeholder` is not a member at all (the guide suggests a signal input if your control wants one), and `stateChanges` is needed only for state kept in plain properties. ## Wiring it up 1. **Provide the token**: `providers: [{provide: MatFormFieldControl, useExisting: BankAccountInput}]`. `useExisting` hands the form field the component instance itself; `useClass` would create a second, unrelated instance. 2. **Give it an id** and bind it to the host with `host: {'[id]': 'id'}`, usually from a static counter. 3. **Expose the form control**. For reactive or template-driven forms, inject `NgControl` with `{optional: true, self: true}` and set `ngControl.valueAccessor = this` in the constructor. Also listing `NG_VALUE_ACCESSOR` in `providers` creates a cyclic dependency, because the component would then inject the very directive that injects it. The `ControlValueAccessor` methods themselves (`writeValue`, `registerOnChange` and the rest) are Angular's forms contract and work as usual. For Signal Forms, expose the bound field as `ngField` and set `ngControl` to `null`. 4. **Report state.** `focused` as a signal set on `focusin` and cleared on `focusout` when focus leaves the host; `empty` and `shouldLabelFloat` as `computed` over the two parts; `required` and `disabled` as signals (an input with `booleanAttribute`, or a signal set from `setDisabledState`). ## Error state that matches the rest of the form A tempting `errorState = ngControl.invalid` paints the field red on first render. To behave like `matInput`, inject **`ErrorStateMatcher`** and the parent `FormGroupDirective`, then evaluate `matcher.isErrorState(ngControl.control, parentForm)` in `ngDoCheck`. Keep it cheap, since it runs on every change-detection pass. Because this `errorState` is a plain boolean that changes over time, emit on `stateChanges` when it flips; a signal-only control would not need to. ## Accessibility and clicks - **`setDescribedByIds(ids)`**: set `aria-describedby` on the element that represents the control, here the `role="group"` wrapper, to `ids.join(' ')`. The form field does not write it for you. Add a `userAriaDescribedBy` member if consumers may pass their own `aria-describedby`, so the field merges rather than overwrites. - **Labelling the group**: inject `MAT_FORM_FIELD` and bind the group's `aria-labelledby` to `getLabelId()`, so the `<mat-label>` names the whole group. - **`onContainerClick()`**: focus the routing input, or the first incomplete part, when the user clicks the padding around the inputs. ## Common mistakes - Implementing `ControlValueAccessor` only and expecting `mat-form-field` to accept the component. - Copying an old article: a mandatory `placeholder`, a `stateChanges` subject for state that is already signals. - Leaving `setDescribedByIds` empty, so screen readers never hear the hint or the error. - Treating `focusout` from the routing input as blur of the whole control while focus moves to the account input.
- Why does adding NG_VALUE_ACCESSOR to the component's providers fail here, and what replaces it?The component injects `NgControl` so it can expose `ngControl` to the form field, while `NgControl` itself injects `NG_VALUE_ACCESSOR`; providing the component under that token closes the loop and Angular reports a cyclic dependency. Drop the provider and assign `this.ngControl.valueAccessor = this` in the constructor when `ngControl` exists.
- When does a v22 custom control still need stateChanges?When any state the form field reads, such as `focused`, `empty`, `disabled` or `errorState`, lives in a plain property that changes over time. The form field reads signal members directly and reacts to them; for plain properties it has no way to know a change happened, so emit on `stateChanges` after each change and complete it on destroy.
- What does controlType give the consumer?The form field adds a class `mat-form-field-type-<controlType>` to its host, so `controlType = 'bank-account'` yields `mat-form-field-type-bank-account`. Consumers can target fields holding this control in their styles without reaching into its internal DOM.
- Implementing ControlValueAccessor is enough to make a component work in mat-form-field.
- MatFormFieldControl in v22 still requires a placeholder and a stateChanges subject.
- Provide the control with useClass so the form field gets its own instance.
- setDescribedByIds can stay empty because the form field sets aria-describedby itself.
- errorState should simply mirror ngControl.invalid.
Assumes Angular Material 22.2; the v22 MatFormFieldControl accepts Signal<boolean> state, makes stateChanges optional and has no placeholder member.