Forms
About
Angular will not automatically detect the inputs and selects.
Angular injects a couple of classes on the inputs and selects.
Best Practices
Mainly use
Reactiveforms.Use
FormBuilderservice to be able to use TypedFormControlsby default.It will thought create
FormControlswithType | null.
To avoid having
nullabletypes, useNonNullableFormBuilderservice.
Details
Foundation Classes
FormControl
FormControlTracks 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
FormGroupDefines a form with a fixed set of form controls that you can manage together.
Its parameters are (in order):
Object of multiple
FormControl,FormGrouporFormArray.
FormArray
FormArrayDefines a dynamic form, where you can add and remove controls at run time.
ControlValueAcessor
Creates a bridge between Angular FormControl instances and built-in DOM elements.
Control States
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
ngFormngForm 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.
Resetting the Form
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()ofngFormon the variable, this will reset thesubmittedof the form to false again.
Last updated
