In Ionic v4, I’m trying to create a picker that will change one of the columns based on another, more or less in the same way ion-datetime does. Since the documentation doesn’t have much about it I’m having quite a hard time with this. I tried to base it on what I’ve seen on ion-datetime’s source code, and it turned out like this:
export class HomePage {
_data: { semana: { text: string; value: any }; mes: { text: string; value: any } };
set data(value: any) {
this._data = value;
}
get data() {
if (this._data) {
return `${this._data.semana.text} semana de ${this._data.mes.text}`;
} else {
return '';
}
}
_currentSelected: any = {};
get currentSelected(): any {
return this._data || this._currentSelected;
}
set currentSelected(val: any) {
this._currentSelected = val;
}
constructor(private pickCtrl: PickerController) {}
months = [
'Janeiro',
'Fevereiro',
'Março',
'Abril',
'Maio',
'Junho',
'Julho',
'Agosto',
'Setembro',
'Outubro',
'Novembro',
'Dezembro'
];
async openPicker() {
const picker: HTMLIonPickerElement = await this.pickCtrl.create({
columns: this.createColumns(),
buttons: [
{
text: 'CONFIRMAR',
handler: data => {
this.data = data
}
},
{ text: 'CANCELAR' }
]
});
picker.addEventListener('ionPickerColChange', async (event: any) => {
const data = event.detail;
const colSelectedIndex = data.selectedIndex;
const colOptions = data.options;
const changeData: any = {};
changeData[data.name] = {
value: colOptions[colSelectedIndex].value
};
this.currentSelected[data.name] = changeData[data.name];
console.log(this.currentSelected);
const columns = this.createColumns();
picker.columns = columns;
picker.forceUpdate();
});
picker.present();
}
createColumns(): PickerColumn[] {
const pickerOptionsMonth: PickerColumnOption[] = this.months.map((month, index) => {
return { text: month, value: index };
});
const pickerColumns: PickerColumn[] = [];
const pickerOptionsSemana: PickerColumnOption[] = [
{ text: '1ª', value: 1, duration: 100 },
{ text: '2ª', value: 2, duration: 100 },
{ text: '3ª', value: 3, duration: 100 },
{ text: '4ª', value: 4, duration: 100 },
{ text: '5ª', value: 5, duration: 100 }
];
if (this.currentSelected.mes && this.currentSelected.mes.value === 1) {
pickerOptionsSemana.splice(4, 1);
}
const selectedIndex = this.currentSelected.semana
? this.currentSelected.semana.value < pickerOptionsSemana.length
? this.currentSelected.semana.value - 1
: pickerOptionsSemana.length - 1
: 0;
pickerColumns.push({
name: 'semana',
options: pickerOptionsSemana,
align: 'right',
prefix: 'Semana:',
columnWidth: '120px',
selectedIndex
});
pickerColumns.push({
name: 'mes',
options: pickerOptionsMonth,
align: 'left',
prefix: 'Mês:',
columnWidth: '220px',
selectedIndex: this.currentSelected.mes ? this.currentSelected.mes.value : 0
});
return pickerColumns;
}
}
My problem is, when one of the options is remove it gives me this error:
And when a new option is added this happens:
Maybe I’ve missed out on something, but I’m really stuck there. Any help would be appreciated.