首页 > 解决方案 > 如何在 Ionic 4 中显式打开日期选择器?

问题描述

我想在单击按钮时打开离子日期时间选择器(或者当我在一个选择器中设置值时,它应该打开另一个日期时间选择器)。

标签: ionic-frameworkionic4

解决方案


不错的解决方法:

  1. 添加日期时间组件并将其隐藏。
  2. 附上它的参考。
  3. 确保手动显示值,因为选择器是隐藏的。

附上代码示例。

html:

<ion-col (click)="datePicker.open()" width-50>
    <ion-icon name="calendar"></ion-icon>

    <div>
        {{ selected.toDate() | amDateFormat:'DD' }} {{ selected.toDate() | amDateFormat:'MMM' }}, {{ selected.toDate() | amDateFormat:'YYYY'}}
    </div>

    <ion-item no-lines hidden="true">
        <ion-datetime  #datePicker
            text-center
            (ionChange)="dateChanged($event)"
            displayFormat="DD MMM, YYYY" 
            [(ngModel)]="date"></ion-datetime>
    </ion-item>
</ion-col>

.ts:

import {Component, ViewChild} from '@angular/core';
import { DateFormatPipe } from 'angular2-moment';
import * as moment from 'moment';

@Component({
    templateUrl: './awesome-compo/awesome.html',
    pipes: [ DateFormatPipe ]
})
export class AwesomeCompo {
    private selected: any = moment();
    private date: any = moment().toISOString();

    @ViewChild('datePicker') datePicker;

    dateChanged(date) {
        const { day, month, year } = date;
        this.selected.year(year.value).month(month.text).date(day.value);
    };
}

详细答案:完整答案


推荐阅读