FormControl represents one form element in Angular’s reactive forms API. It gives a component direct access to the element’s value, enabled state, interaction state, and validation state. Use it when form behavior needs to be managed in code rather than only through template directives. section 21.2 section 21.5
Bind a single input
Import ReactiveFormsModule and bind an input to a component property: nameField = new FormControl({ value: '', disabled: false }); <input name="name" [formControl]="nameField" /> The [formControl] binding connects the input to nameField; ngModel is not used for this binding. Call nameField.setValue(newName) to change the input from the component, such as when loading a product for editing. section 21.3
The control exposes separate ways to work with its value, interaction, and validation:
- Read value, call setValue(value), or subscribe to valueChanges. Set updateOn to change (the default), blur, or submit to choose when updates occur. section 21.3 section 21.3.1
- Read enabled or disabled and call enable(), disable(), or reset(). The touched/untouched and dirty/pristine properties describe interaction; matching markAs… methods change those states manually. section 21.3 section 21.3.2
- Configure validators in the constructor or manage them with validator methods. Read valid, invalid, status, and errors, or subscribe to statusChanges when validation state changes. section 21.3.3
Table 21.3. Useful basic FormControl members
|
Name
|
Description
|
|
value
|
This property returns the current value of the form control, defined using the
any type.
|
|
setValue(value)
|
This method sets the value of the form control.
|
|
valueChanges
|
This property returns an
Observable<any>, through which changes can be observed.
|
|
enabled
|
This property returns
true if the form control is enabled.
|
|
disabled
|
This property returns
true if the form control is disabled.
|
|
enable()
|
This method enables the form control.
|
|
disable()
|
This method disables the form control.
|
|
reset(value)
|
This method resets the form control, with an optional value. The form control will be reset to its default state if the value argument is omitted.
|
The basic-member table is a quick reference for reading values, observing changes, enabling or disabling an input, and resetting it. section 21.3
For a product form with name, category, and price inputs, place the controls in a FormGroup and bind each input with formControlName. This avoids a separate component property for every control. One control can also govern another: the category input can remain disabled until the name input passes validation. With formControlName, obtain an individual control through the group when its errors are needed in a template. section 21.3.4 section 21.4.1 section 21.4.3
