Hello,
I’m using Ionic 8 with Angular 18. In a new component, I’m using ion-picker for the first time. I’m trying to bind a variable to it with [(ngModel)]. That doesn’t seem to work. I tried it like this:
<ion-picker [(ngModel)]="test">
<ion-picker-column>
<ion-picker-column-option value="test 1">Test 1</ion-picker-column-option>
<ion-picker-column-option value="test 2">Test 2</ion-picker-column-option>
<ion-picker-column-option value="test 3">Test 3</ion-picker-column-option>
</ion-picker-column>
</ion-picker>
I also tried to put ngModel on ion-picker-column. In both cases I get the following error in the console:
ERROR TypeError: Cannot read properties of null (reading ‘writeValue’)
That probably means that ion-picker doesn’t support ngModel. Is that correct? If yes, is there a special reason? ion-datetime supports it.
You’re correct that ion-picker
does not support [(ngModel)]
binding. The ion-picker
component is designed a bit differently compared to other Ionic components like ion-datetime
.
You can use event binding and a property to handle the selected value.
async openPicker() {
const picker = await this.pickerController.create({
columns: [
{
name: 'options',
options: [
{ text: 'Test 1', value: 'test 1' },
{ text: 'Test 2', value: 'test 2' }
],
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
},
{
text: 'Confirm',
handler: (value) => {
this.test = value.options.value; // Here you will get the value.
},
},
],
});
await picker.present();
1 Like
Hey, thanks for the reply!
According to the docs of Ionic 8, the picker controller is only available in the legacy version of ion-picker. So I don’t want to introduce it into my app.
My solution now is to listen to the ionChange event of ion-picker and upate the variable from there.