zfireear
zfireear

Reputation: 63

how to setup a userform in lastest ionic 2

I try the ionic 2 and form tutorial Forms with FormBuilder ,but it didn't work.Either it can't find the name todo,or I use DI to declare it in constructor but it throws a error no provider for FormGroup.so how to use a formBuidler to create a form?thanks.here are my code: login.ts:

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


@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class Login {

  constructor(public navCtrl: NavController,
              public loadingCtrl: LoadingController,
              public formbuilder:FormBuilder,
              public userform:FormGroup,
              public username:FormControl,
              public password:FormControl
              ) {}



  ionViewLoaded() {
                console.log('Hello Login Page'); 
               this.userform = this.formbuilder.group({ 
                username: ['', Validators.required], 
                password: ['',Validators.required] 
            }); 
        }
}

login.html:

<ion-header>
   <ion-navbar>
       <ion-title>
           User Login
       </ion-title>
   </ion-navbar>
</ion-header>
<ion-content >
    <form [formGroup]="userform" (ngSubmit)="onCommit()">
        <ion-item>
            <ion-label>username</ion-label> 
            <ion-input type="text" formControlName="username" name="username"></ion-input>         
        </ion-item>
         <ion-item>
            <ion-label>password</ion-label> 
            <ion-input type="password" formControlName="password" name="password"></ion-input> 
        </ion-item>
    </form>
    <div padding>
         <button ion-button type="submit" block  
        [disabled]="!userform.controls.username.valid || !userform.controls.password.valid" 
        >login</button>
    </div>
</ion-content>

Upvotes: 2

Views: 543

Answers (2)

Karlis Filipsons
Karlis Filipsons

Reputation: 135

Adding to mosca90 answer. You can add

<p *ngIf="!isValid('user') && myForm.controls.user.touched" color="danger" padding-left>Insert an username"</p>

to show errors if user has not done something and goes to the next field instead of showing an error in the users face while he is still typing.

Upvotes: 0

mosca90
mosca90

Reputation: 999

Ionic2, RC1.

1 - Import:

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

2 - Your .ts file:

export class Registration {
    myForm: FormGroup;
    userInfo: {user: string, password: string} = {user: '', password: ''};

    constructor(public formBuilder: FormBuilder) {

        this.myForm = this.formBuilder.group({
            'user': ['', [Validators.required]],
            'password': ['', [Validators.required, this.passwordValidator.bind(this)]]
        });
    }

    passwordValidator(control: FormControl): {[s: string]: boolean} {
        if (control.value !== '') {
            if (!control.value.match(/^(?=.*\d).{4,30}$/)) {
                return {invalidPassword: true};
            }
        }
    }

    isValid(field: string) {
        let formField = this.myForm.get(field);
        return formField.valid || formField.pristine;
    }

    onSubmit() {
        console.log('submitting form');
    }
}

3 - Your .html file:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
    <ion-item>
        <ion-label>User</ion-label>
        <ion-input [(ngModel)]="userInfo.user" formControlName="user" type="text"></ion-input>
    </ion-item>
    <p *ngIf="!isValid('user')" color="danger" padding-left>Insert an username"</p>

    <ion-item>
        <ion-label>Password</ion-label>
        <ion-input [(ngModel)]="userInfo.password" formControlName="password" type="password"></ion-input> 
    </ion-item>
    <p *ngIf="!isValid('password')" color="danger" padding-left>Invalid password. At least 4 chars and a number.</p>

    <button ion-button type="submit" [disabled]="!myForm.valid">Create Account</button>
</form>

This should work. At least in my project run like a charm.

Other infos can be found here: Ionic2 Form

Hope it helps!

Upvotes: 1

Related Questions