背景:前两天在用ionic4 UI写个demo,在用到组件ion-picker的时候,碰到个需求,需要动态设定该组件的默认选中项(即:每次打开组件的选中项是上一次操作的选中值),看过官网例子picker都知道,官网上每次打开都默认选中的是第一项
在网上找了几天没找到解决办法,最终在大佬(IT晴天)指点下,知道了每列都有selectedIndex属性,可以设置每列的选中项,感谢!!!
最终效果如下图:
picker.gif
虽然可以在columns中的数据上设定每列的选中项,但并不能达到我们想要的效果,因此,设定columns中的数据需要写成一个方法 generateColumns
,以实现动态的改变默认选定值
HTML如下:
<ion-item>
<ion-label>所选项:</ion-label>
<ion-input [value]='pickerVal' color="primary"></ion-input>
<ion-button (click)="openPickerCard()">
点击选卡
</ion-button>
</ion-item>
ts如下:
pickerVal: string = '1.1text';
columnData: any[] = [
{ name: '1.1text', code: '001' },
{ name: '1.2text', code: '002' },
{ name: '1.3text', code: '003' },
{ name: '1.4text', code: '004' },
{ name: '1.5text', code: '005' },
]
constructor(public pickerCtrl: PickerController) { }
ngOnInit() {
console.log(`进入选择卡组件了`);
}
openPickerCard() {
this.openPicker(this.pickerVal, (val: any) => {
console.log(val);
console.log(val.data.value);
this.pickerVal = val.data.text;
})
}
async openPicker(defaultval?: string, okBackFun?: any) {
const picker = await this.pickerCtrl.create({
columns: this.generateColumns(defaultval),
buttons: [
{ text: '取消', role: 'cancel' },
{
text: '确定', handler: (value) => {
okBackFun && okBackFun(value);
}
}]
})
picker.present();
}
private generateColumns(defaultval?: string): PickerColumn[] {
const columns = [];
const pickerCol: PickerColumn = {
name: 'data',
options: this.columnData.map(province => ({ text: province.name, value: province.code, disabled: false, duration: 100 }))
};
let Index = this.columnData.findIndex(option => option.name === defaultval);
pickerCol.selectedIndex = Index === -1 ? 0 : Index;
columns.push(pickerCol);
return columns;
}
到此,即大功告成!
网友评论