Dilip
Dilip

Reputation: 668

FormGroup item input not updating on Ionic 2

I'm new to Angular 2. I'm trying to create a simple form using FormBuilder & FormGroup. But for some reason whatever I'm entering in the username field from view is not updating on my component, can't see new value when I'm clicking submit button. My view and component code is as below, can someone please point me what is the issue.

login.ts

import { Component} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
selector:"login-page",
templateUrl: "login.html"
})

export class LoginPage {
    loginForm : FormGroup;
    constructor(formBuilder :FormBuilder) {
        this.loginForm = formBuilder.group({
            'username':[
                '',
                Validators.required
            ]
        });
    }

     validate() : boolean {
         if (this.loginForm.valid) {
             return true;
         }
     }
    submit() : void {
        if (!this.validate()) {
            console.info("Invalid input")
        }
        let control = this.loginForm.controls['username'].value;
        console.log(control);
    }
}

login.html

<ion-header style="text-align:center">
  <ion-navbar>
    <ion-title>Please login</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>

    <h3 style="text-align:center">Welcome to your first Ionic app!</h3>


   <form class ="list" [formGroup]="loginForm" (ngSubmit)="submit()">
      <ion-item class="loginInput center">
          <ion-label floating>Email</ion-label>
          <ion-input type="text" name='username' ngControl="username" ></ion-input>
      </ion-item>
      <div class="loginBtn"><button  style="width: 140px" ion-button type="submit">Login</button></div>
   </form>

</ion-content>

Upvotes: 2

Views: 1172

Answers (2)

Sampath
Sampath

Reputation: 65870

You need to do below changes.

.ts

loginForm : FormGroup;

constructor(formBuilder :FormBuilder) {
   this.loginForm = formBuilder.group({
      username:['',Validators.required]
   });
}

.html

 <form class ="list" [formGroup]="loginForm" (submit)="submit(loginForm)">
    <ion-item class="loginInput center">
       <ion-label floating>Email</ion-label>
       <ion-input type="text" name='username' formControlName="username" ></ion-input>
    </ion-item>
    <div class="loginBtn">
       <button style="width: 140px" ion-button type="submit">Login</button>
    </div>
 </form>

Upvotes: 1

Prerak Tiwari
Prerak Tiwari

Reputation: 3466

Change

<ion-input type="text" name='username' ngControl="username" ></ion-input>

to

<ion-input type="text" [formControl]="loginForm.controls['username']" ></ion-input>

Upvotes: 3

Related Questions