In this section, we will learn complex form validation through ngForm and ngControl. We will create service file (MyFormService) where we define our form class. This class will have all the form field. Validation applied to the following field.
- The name field is required.
- Validate comment field is required and the user must enter a minimum of four characters.
- The user must agree to the terms and conditions via toggle input.
Once all above conditions are made and user click on submit button. We will send all the input field of the form to display on the second page.
To achieve our form validation apps, we need to follow certain step
Step 1: ionic start MyFormValidation blank –v2
Step 2: mkdir ./src/services
Create a myform.ts, add the following code to define MyformService class. We need to add MyFormService as provider in app.module.ts as providers: [MyFormService]
Step 3: We need to add form in our home.hmtl. We have temporary local Boolean variable isSubmitted, we will use this variable to check whether the form is submitted or not.
In our home.html # is used to make local variable.#f variable refers to ngForm which is automatically created by angular. This is a special object that contains all information related to current form. The (ngSubmit) an event will trigger the onSubmit(f) method whenever the user clicks on submit button of our form.
Step 4: We need to add following code in home.ts
We will add style to our home.scss
Step 5: We will create thankyou page, This page will accept and display the input field of our form of home.html.
>>ionic g page thankyou.
Add following code in our thankyou.ts
Add the following code in home.html