Javascript

New Changes Ionic 2 Forms with Examples

Preamble: You used Ionic 2 Forms about 3 months ago, probably. All worked nicely. You spinned up a new project today, and everything you write is breaking and causing error with regards to forms. You’re not alone. Welcome. This is for you. A new look at Ionic 2 Forms with examples.

This article considers these:

  • Template-driven forms (I call it Implicit form creation)
  • Using FormBuilder
  • Using FormBuilder with Validators

Ionic 2 Forms are Angular Forms. And Angular 2 Forms are in recent months under constant development and iteration, to the extent of many breaking changes. Although my previous blog post worked for some months, I started getting emails of the project breaking under new changes.

I am happy to update the project to the new way of in Ionic 2 Forms, and I do a bit of explanation in this.

In this short article, I wish to share with you, new steps required to get a working form in Ionic 2 in Beta.11 with AngularJS 2 RC4, with a working example to play with.

Take a seat, and let’s enter the Hadron Collider for some …. ? You guessed right!

Many are broken, for good!

At the end of a relatively long post, giving reasons for some why’s and why not, a list of deprecated form APIs are listed, along with their shiny new counterparts that are now going to rule the house.

The list indicates the new name to use along with the deprecated name (name used formerly) in brackets. Now this list is probably not all there is to be deprecated.

REACTIVE_FORM_DIRECTIVES:

  • formGroup (deprecated: ngFormModel)
  • formControl (deprecated: ngFormControl)
  • formControlName (deprecated: ngControl)
  • formGroupName (deprecated: ngControlGroup)
  • formArrayName (deprecated: ngControlGroup)
  • FormControl() (deprecated: Control)
  • FormGroup() (deprecated: ControlGroup)
  • FormArray() (deprecated: ControlArray)
  • FormBuilder (same)
  • Validators (same)

We won’t be using all the above, just like we didn’t in the previous example. However, having them in mind is worth is, as you’ll be able to turn and twist as and when you need.

See the entire rc4 changelog here

Ionic 2 Forms with Examples

 

Most basic of Forms

Although I used to call this approach below ‘Implicit’ and the other way using FormBuilder as ‘explicit’, I think the right terms to use are ‘Template Driven’ and ‘Model Driven’ respectively.

The new approach is equally simple and straightforward. Let’s allow the code to speak. Let’s say this is our basic-form.html

   <ion-list inset>
        <form #myForm='ngForm' (ngSubmit)="onSubmit(myForm)">
            <ion-item>
                <ion-label floating>Subject</ion-label>
                <ion-input type="text" [(ngModel)]="subject" name="subject"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label floating>Message</ion-label>
                <ion-textarea type="text" [(ngModel)]="message" name="message"></ion-textarea>
            </ion-item>
            <button block>
                <ion-icon name="add"></ion-icon>Add</button>
        </form>
    </ion-list>

The above is one way to create an Ionic 2 forms if you’re using Beta 11 with AngularJS RC4. Nothing much changes, except the use of [(ngModel)] instead of ngControl. Remember from above, ngControl is deprecated.

Our basic-form.js might look as straightforward as this. It doesn’t get simpler than this, does it?

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/basicform/basicform.html',
})
export class BasicformPage {
  private myData: any;
  constructor(private navCtrl: NavController) {  }

  onSubmit(formData) {
    if(formData.valid) {
      console.log(formData.value);
      this.myData = formData.value;
    }
  }

}

Using the FormBuilder

I love the FormBuilder because it provides many more goodies and simplifies the life of the developer a ton. For instance, just like as done in the older way, using the FormBuilder can go like this (without validations):

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  templateUrl: 'build/pages/buildform/buildform.html',
})
export class BuildformPage {
  myForm: FormGroup;
  private myData: any;
  constructor(private navCtrl: NavController, private builder: FormBuilder) {
    this.myForm = builder.group({
      'subject': '',
      'message': ''
    })
  }

  onSubmit(formData) {
    console.log('Form data is ', formData);
    this.myData = formData;
  }
}

The only difference is the importations we do. We simply indicate what type our myForm should be, which is the type of a FormGroup then with that in hand, we simply go ahead to build a form group.

Then in our forms, something like this:

    <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
        <ion-item>
            <ion-label floating>Subject</ion-label>
            <ion-input type="text" formControlName="subject" name="subject"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Message</ion-label>
            <ion-textarea type="text" formControlName="message" name="message"></ion-textarea>
        </ion-item>
        <button block>
            <ion-icon name="add"></ion-icon>Add</button>
    </form>

With Validators

If you wish to throw in validation using Validators, you could go something like:

.... 
 constructor(private navCtrl: NavController, private builder: FormBuilder) {
    this.myForm = builder.group({
      'subject': ['', Validators.required],
      'message': ['', Validators.required]
      // 'subject': '',
      // 'message': ''
    })
  }
....

Then in your templates,

    <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)" novalidate>
        <ion-item>
            <ion-label floating>Subject</ion-label>
            <ion-input type="text" formControlName="subject" name="subject"></ion-input>
        </ion-item>
        <p [hidden]="myForm.controls.subject.valid" danger padding-left>Subject is empty</p>
        
        .....

        <button block [disabled]="!myForm.controls.subject.valid || !myForm.controls.message.valid">
            <ion-icon name="add"></ion-icon>Add</button>
    </form>

There you go!

Check out the new branch I created on the existing repo for the changes discussed above in action. Remember to check out the typescript branch specifically for the new way of ‘forming’ changes.

However, the older way of working with forms in Ionic 2 exist in the master branch, and you’re free to play with whichever interests you depending on what versions of Ionic 2 you’re using.

I will be keeping an eye on any changes regarding forms and keep you updated.

Thank you, and hope to see you in the next one! Any questions, feedback? Please lemme know in the comments below!

Resources

For more on forms in AngularJS 2 in general, consider following these articles:

 

Related Articles

Back to top button