How to make a form in ionic 2

12,572

To begin with, let's assume a simple case of creating a login form.

  • form:

    • (input) username

    • (input) password

    • (button) login

Your .html file:

        <form [ngFormModel]="loginForm" (submit)="login($event)">
            <ion-input stacked-label>
                <ion-label>Username</ion-label>
                <input type="text" ngControl="username">
            </ion-input>

            <ion-input stacked-label>
                <ion-label>Password</ion-label>
                <input type="password" ngControl="password">
            </ion-input>

            <div padding>
                <button block type="submit" [disabled]="!loginForm.valid">Login</button>
            </div>
        </form>

In your .js file:

import {FormBuilder, Validators} from 'angular2/common';

export class LoginPage {

  constructor(form: FormBuilder) {
    // Create a new form group
    this.loginForm = form.group({ // name should match [ngFormModel] in your html
      username: ["", Validators.required], // Setting fields as required
      password: ["", Validators.required]
  }

  // This is called on form submit
  login(event) {
    console.log(this.loginForm.value) // {username: <usename>, password: <password> }
    event.preventDefault();
  }

}

Reference

Share:
12,572
Arash
Author by

Arash

Updated on July 13, 2022

Comments

  • Arash
    Arash almost 2 years

    I want to try ionic/angular 2, and I can't figure out how to create a form. How can I do this?