Ionic 3 - One/Two-Way Binding Usage


#1

The purpose of the app is to check whether a student is absent or present. For testing purposed. I have this code on my app.

HTML

<ion-list>
  <ion-list-header>
    Students
  </ion-list-header>

  <ion-item>
    <ion-input [(ngModel)]="attendance.studentName" type="text"></ion-input>
    <ion-select item-end [(ngModel)]="attendance.status">
      <ion-option value="Present">Present</ion-option>
      <ion-option value="Absent">Absent</ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-input [(ngModel)]="attendance.studentName" type="text"></ion-input>
    <ion-select item-end [(ngModel)]="attendance.status">
      <ion-option value="Present">Present</ion-option>
      <ion-option value="Absent">Absent</ion-option>
    </ion-select>
  </ion-item>

</ion-list>

TS

attendance: any = {
    'studentName': [],
    'status': []
}

Current, I am using two-way binding “[(ngModel)]” for the input and select tags. But when I type and select an option, both of these are being edited. But when I use one-way binding “[ngModel]”. The problem of both inputs and select options being edited at the same time is gone. But I get nothing on console.log


#2

This is because u have two ui elements control one variable

And this behavior is as designed in angular

U need to use ngFor in the template to loop through an array of students and have the ngModel bind to the item’s property

Check ngFor on angular.io and the template binding syntax on angular.io to get a better understanding and to avoid issues like this