I want a dropdown in my form. I know how to add options in dropdown statically, but, I want it to be dynamic.
My code
<ion-item>
<ion-label>Select Type</ion-label>
<ion-select [(ngModel)]="selectedvalue" #item>
<ion-option *ngFor="let item of items" [value]="item">{{item}}</ion-option>
</ion-select>
</ion-item>
I have written the html code for this. But I don't know what to do in my .ts file. How to assign values to items?
What you need to do in your code is define the options array and a variable for the selected option in Page.ts and at some point populate it with option objects. So define the array like this... (i'm using TypeScript definitions for each property here because why not)
export class Page {
selectedValue: number;
optionsList: Array<{ value: number, text: string, checked: boolean }> = [];
constructor() { }
Alternatively just something like this should also work...
optionsList: any[] = [];
And then populate the array with option objects (each object should have 2 properties and optionally a 3rd if you want to pre-select an option).
Where you do this will depend on if it is being populated asynchronously or not. For this example I will just do it in the constructor...
constructor() {
this.optionsList.push({ value: 1, text: 'option 1', checked: false });
this.optionsList.push({ value: 2, text: 'option 2', checked: false });
}
And your HTML code should look something like this...
<ion-select [(ngModel)]="selectedvalue">
<ion-option *ngFor="let item of optionsList" value="{{item.value}}" checked="{{item.checked}}">{{item.text}}</ion-option>
</ion-select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With