I want to try ionic/angular 2, and I can't figure out how to create a form. How can I do this?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With