Forms can be implemented in three ways in Ionic:
- Forms with Templates
- Forms with FormBuilder
- [(ngModel0]: This is a simple API that binds and passes the object to the class. Templates uses ngModels to bind the object and ngSubmit to submit the form. When using ngModel, “name” property is required for the form fields. An example of how the ngModel is used in forms.
- Forms with Templates This way of Form implementation uses the reference to the form instead of the model of the form. The values are pulled directly from the form itself, which is similar to the ngModel way of implementation. The main difference is that the ngModel uses the model of the form, but the template uses the form reference itself.
- Forms with FormBuilder: Forms are created in the class and their logic is also maintained in the class. Template should import the FormBuilder from angular/forms. Also, template would use the formGroup and formControlName as shown below. FormBuilder is a helper service which creates the instance of ControlGroup which we can refer to as “form.”
Example for creating new form apps:
Angular 2’s ngModel directive allows us to implement a concept known as two-way data binding to form input fields in our templates. Two-way data binding is a term used to describe the association between the value of a template input field and the value of a variable in the component class.
Using the ngModel directive values can be set in both directions, hence the term two-way data binding.
Step to follow:
Step 1: ionic start simpleForm blank –v2
npm install // Install additional node modules
Add the following code in home/home.html
Each of the 3 fields in our above form has ngModel directive attached to it whose
value links that template input field to a specified property in the component
Step 2: Add the following code in app/home/home.ts
You’ll notice that we set a public property named details which are an object that contains the name, occupation and platform keys that the template input fields reference through the ngModel directives.