Angular Reactive Forms will let your application listen to the changes of input values within the forms as an Observable and react to those changes accordingly. This is useful for making a real-time form validation for Ionic application. In this tutorial, we will be making a form that validates the user input in real-time.
- Create a New Ionic Project
- Set Up Reactive Form
- Create the Form
- Validate the Form
- Result
- Complete Source Code
- Video
This tutorial was made with Angular + Ionic CLI v4 and above.
1. Create a New Ionic Project
Start this project by creating new blank Ionic project.
2. Set Up Reactive Form
Since we are using the reactive form, go to home.module.ts
and replace the FormsModule
with ReactiveFormsModule
.
Add the following changes inside
home.module.ts
.
After that, go to home.page.ts
and import FormBuilder
from angular/forms
.
Add the following changes inside
home.page.ts
.
3. Create the Form
Creating form control instances manually is tedious especially for a complex form. With FormBuilder
, it reduces the amount of boilerplate when building a form. Read more about FormBuilder.
The following is an example of the how using the
FormBuilder
reduces the amount of boilerplate used for the same task.
For this tutorial, the form consists of a name, email, phone number, and address. We are also going to group together several inputs to make up a complete address input.
Add the following
FormBuilder
group insidehome.page.ts
For submission, create a function named submit()
for form submission. The function will print the value of the submission to the console screen.
Add the following function inside
home.page.ts
.
Create the form inside home.page.html
using form
tag and specify the form identifier with [formGroup]="registrationForm"
.
Map the ion-input
with the FormControl
using formControlName
. As for the FormGroup
, use formGroupName
.
For submission, use event-emitter ngSubmit
to execute the submit()
function that we created earlier.
Add the following changes inside
home.page.html
.
4. Validate the Form
For form validation, go to home.page.ts
and import Validators
from angular/forms
.
Add the following changes inside
home.page.ts
.
Create a getter for every input we can call it easily inside home.page.html
.
Add the following getters inside
home.page.ts
.
For an error message, we are going to specify it inside the home.page.ts
.
Add the following inside
home.page.ts
.
Insert an error messages below every input.
Add the following changes inside
home.page.html
.
Change the color of the error message inside home.page.scss
.
Add the following changes inside
home.page.scss
.
5. Result
6. Complete Source Code
Feel free use the complete source code inside your awesome project.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.