Search code examples
angularionic-frameworkformbuilder

Ionic And Angular 5 form builders and groups is not reading values


I am learning ionic with angular.

I created a login form:

<form [formGroup]="login">
    <ion-item>
      <ion-label>
        <ion-icon android="android-contacts" name="contacts"></ion-icon>
      </ion-label>
      <ion-input type="text" value="" name="username" [formControlName]="'username'" ></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>
        <ion-icon android="android-unlock" md="md-unlock"></ion-icon>
      </ion-label>
      <ion-input type="password" value="" name="password" [formControlName]="'password'" placeholder="Password"></ion-input>
    </ion-item>
  </form>
  <button ion-button full (click)="onLoginClick()" [disabled]="login.valid" >LOGIN</button>

And here I declared the form group with controls:

constructor(public fb: FormBuilder, public authService: ApiAuthProvider, public altCtrl: AlertController, public navCtrl: NavController, 

    public navParams: NavParams) {

    this.login = fb.group({
      username: new FormControl(['u', Validators.required]),
      password: new FormControl(['p', Validators.required])
    })
  }

There is no error at ionic serve, but the login button is not disbaled, and can't read what I typed in username input when I click on the login button:

onLoginClick(){
    console.log(this.login['username']);
}

It always display undefined as result.

By the way, working with form builders in ionic is the same when working with a pure Angular app ?


Solution

  • You have to access form control value like

    onLoginClick(){
        console.log(this.login.get('username').value);
    }
    

    And also you are trying to disable it when form is valid. You should check for invalid

    <button ion-button full (click)="onLoginClick()" [disabled]="login.invalid" >LOGIN</button>
    

    EDIT :

    Modify form control parameters this way : You are passing them as an array. They should be two separate parameters.

    this.login = fb.group({
          username: new FormControl('u', Validators.required),
          password: new FormControl('p', Validators.required)
    })
    

    You may add array of validators if you have multiple validators like

    new FormControl('u', [Validators.required, Validators.maxlength])