Amaury Laroze
Amaury Laroze

Reputation: 217

How to preselect ion-option

I'm new in Ionic and i try to use the ion-select dynamically with preselect option.

I just want edit my profile with some value. In this example i can set multiple language that the user can speak.

First i get all languages set in my database with my API and i set my result in var LanguagesData. My result in console.log

Second i get currently languages spoken by my user and set the result in currentLanguages My result in console.log

Third my code :

<ion-select name="languages" [(ngModel)]="currentLanguage" multiple="true">
     <ion-option *ngFor="let language of languagesData" [value]="language">{{language.language}}</ion-option>
</ion-select>

My values are not preselect. If i replace [(ngModel)]="currentLanguage" by [(ngModel)]="LanguagesData" all values are preselect.

Can you explain me what i did wrong ?

Thanks.

Upvotes: 0

Views: 580

Answers (2)

Amaury Laroze
Amaury Laroze

Reputation: 217

I resolve my problem with a tricks (i'm not proud of it). Currently i get my 2 arrays of data from api call. If i use the base array it does not work. But if i do someting like that :

let i = 0;
                let j = 0;

                while (i < this.currentLanguage.length) {
                  while (j < this.languagesData.length) {

                    if (this.currentLanguage[i].id == this.languagesData[j].id)
                      this.finalLanguage.push(this.languagesData[j]);
                    j += 1;
                  }
                  j = 0;
                  i += 1;
                }

It works when i use finalLanguage instead of currentLanguage. I don't really understand why ...

Upvotes: 1

Sharat K S
Sharat K S

Reputation: 17

<ion-select name="languages" [(ngModel)]="currentLanguage" multiple="true">
     <ion-option *ngFor="let language of languagesData" [value]="language.language">{{language.language}}</ion-option>
</ion-select>

You were missing [value]="language.language"

Hope it solves your proble.

Upvotes: 0

Related Questions