ion-picker实际开发中肯定多处使用,所以封装成服务的形式调用
新建picker.service服务模块 ionic g service picker
import { Injectable, Component, OnInit } from '@angular/core'; import { PickerController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class PickerService { constructor(public pickercontroller: PickerController) {} async openPicker(numColumns = 1, numOptions = 5, multiColumnOptions,callback) { const picker = await this.pickercontroller.create({ columns: this.getColumns(numColumns, numOptions, multiColumnOptions), buttons: [ { text: '取消', role: 'cancel' }, { text: '確定', handler: value => { // console.log(`Got Value ${value}`); callback(JSON.stringify(value)) } } ] }); await picker.present(); } getColumns(numColumns, numOptions, columnOptions) { let columns = []; for (let i = 0; i < numColumns; i++) { columns.push({ name: `col-${i}`, options: this.getColumnOptions(i, numOptions, columnOptions) }); } return columns; } getColumnOptions(columnIndex, numOptions, columnOptions) { let options = []; for (let i = 0; i < numOptions; i++) { options.push({ text: columnOptions[columnIndex][i % numOptions], value: i }); } return options; } }
在组件中使用:
html中:
ts中:
import { Component, OnInit } from '@angular/core'; import { PickerController } from '@ionic/angular'; import { PickerService } from '../picker/picker.service'; @Component({ selector: 'app-head1', templateUrl: './head1.page.html', styleUrls: ['./head1.page.scss'] }) export class Head1Page implements OnInit { Options: any = { header: '開放身份', subHeader: 'Select your favorite color' }; public roleOptions = [['全部', '老師', '學生', '家長']]; public roleText = '開放身份'; //选择的角色 public subjectOptions = [['全部學科', '體育', '科學', '語文', '數學', '英語', '音樂', '美術', '品德與生活', '信息技術', '計算機']]; public subjectText = '全部學科'; //选择的学科 constructor(public pickercontroller: PickerController, public pickerService: PickerService) {} ngOnInit() {} pickerFn($start, $length, $option, type) { let that = this; this.pickerService.openPicker($start, $length, $option, function(result) { let vals = JSON.parse(result)['col-0'].text; switch (type) { case 'role': that.roleText = vals; break; case 'subject': that.subjectText = vals; break; default: break; } }); } }