Forms
Last updated
Last updated
Angular will not automatically detect the inputs and selects.
Angular injects a couple of classes on the inputs and selects.
Mainly use Reactive
forms.
Use FormBuilder
service to be able to use Typed FormControls
by default.
It will thought create FormControls
with Type | null
.
To avoid having nullable
types, use NonNullableFormBuilder
service.
FormControl
Tracks the value and validation status of an individual form control (input).
Its parameters are (in order):
The initial value.
Array of Validators.
Array of async Validators.
FormGroup
Defines a form with a fixed set of form controls that you can manage together.
Its parameters are (in order):
Object of multiple FormControl
, FormGroup
or FormArray
.
FormArray
Defines a dynamic form, where you can add and remove controls at run time.
Creates a bridge between Angular FormControl
instances and built-in DOM elements.
These are classes added to the element, so you can define custom CSS for them.
The form
itself will also receive these state classes.
ng-touched
: The control has been visited, even clicked (had focus on).
ng-untouched
: The control hasn't been visited yet.
ng-dirty
: The control's value has been changed.
ng-pristine
: The control's value hasn't been changed.
ng-valid
: The control's value is valid.
ng-invalid
: The control's value isn't valid.
ngForm
ngForm
has a submitted value on the <form>
, after you <form #thisForm="ngForm">
, that is useful if you want to display error only after the form has been submit.
You can reset the form values
and states
by calling .reset()
method.
You may provide as parameter values to be used.
Otherwise it will the the initial values as default.
But these will only reset the groups and controls validations and values.
To reset the #form
itself from have been submitted
you will have to:
Provide the <form #thisForm="ngForm">
with a Local Template Reference.
Access the reference with a viewChild()
or access it on the (ngSubmit)="handleSubmit(thisForm)"
function.
Call resetForm()
of ngForm
on the variable, this will reset the submitted
of the form to false again.