<ion-select> with *ngFor

I have a simple ion-select with 2 strings that I want to show as options

strings:Array<string>;
selected:string;

constructor(){
    this.strings = new Array<string>();
    this.strings.push('a');
    this.strings.push('b');
}

and the html

<ion-select placeholder="Select" [(ngModel)]="selected">
    <ion-option *ngFor="let item of strings" value="item">{{item}}</ion-option>
</ion-select>

The options are correctly shown but when I select an option and confirm it selects all the other options as well. Why is it happening?

3 Likes

Hello!

Because you’re neither using property binding on value nor string interpolation when adding item as value
Therefore both of your options will get “item” as there value

do it like this:

<ion-select placeholder="Select" [(ngModel)]="selected">
    <ion-option *ngFor="let item of strings" value="{{item}}">{{item}}</ion-option>
</ion-select>`

or

<ion-select placeholder="Select" [(ngModel)]="selected">
    <ion-option *ngFor="let item of strings" [value]="item">{{item}}</ion-option>
</ion-select>`

That’s it! Silly mistake of my part :sweat:
Thank you so much!!!

just change your html from

value="item"

to

value="{{item}}"

Also, to be able to have others read you code easily, never use Hungarian notation.

strings:Array<string>;

Always make your variables meaningful. In the case that you can’t, make them generic; just never name a var “strings”, “myArray”, “myList”, “tuples”, “numbers”, etc.

Yeah, thanks for the tip.
I just did it to post the code :grin:

1 Like

Hi,

I tried this example, but it seems that ngFor isn’t available for tag anymore?

regards
Meex

Hello! Saved my day…

Thanks a lot … example code worked for me…

Can anyone help in this?