angularionic-frameworkselect

ion-select preselection doe not work with [(ngModel)]


I use this code in ngOnInit in order to get all institutions of user and if it is only one institution than set it in <ion-select/>.

private user: User;
public institutionsOfUser: Array<Institution>;
public institutionOfUser: Institution;

ngOnInit() { 
this.authService.getUser().then(response => {
  this.user = response;
  if(this.user == null || this.user.id == null || this.user.id.length == 0) {
    return;
  }
  this.userService.getInstitutionsOfUser(this.user.id, ApplicationModuleTypeEnum.RECORD_REPORT).subscribe(response => {
    this.institutionsOfUser = response;
    if(this.institutionsOfUser != null && this.institutionsOfUser.length == 1) {
      this.institutionOfUser = this.institutionsOfUser[0]; // set if only one institution
    }
  }, error => {
    console.log(error);
  });
});
}

In the html I have the following code:

<ion-list lines="none" style="max-width:350px;">
  <ion-item>
    <ion-select label="Apotheke" okText="OK" cancelText="Schliessen" aria-placeholder="Apotheke" [(ngModel)]="institutionOfUser">
      <ion-select-option *ngFor="let institution of institutionsOfUser" value="{{institution}}"><span translate>{{institution.institutionName}}</span></ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

I thought that if I set this.institutionOfUser = this.institutionsOfUser[0]; than in ion-select this institution should be preselected but it isn't. What I'am doing wrong?


Solution

  • You have to use [value] binding instead of using {{}} this will solve your issue.

    <ion-select
      label="Apotheke"
      okText="OK"
      cancelText="Schliessen"
      aria-placeholder="Apotheke"
      [(ngModel)]="institutionOfUser"
    >
      <ion-select-option
        *ngFor="let institution of institutionsOfUser"
        [value]="institution"
        ><span translate>{{ institution.institutionName }}</span></ion-select-option
      >
    </ion-select>
    

    Stackblitz Demo