简体   繁体   中英

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 ?

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])

You can get the value of the form using

this.login.value ;

If your are using this in the html do like this.

{{login.value | json}}

Or you can get value of a specifica control using\\

this.login.get('controlName).value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM