LoginSignup
0
2

More than 5 years have passed since last update.

【ionic】カレンダーの実装

Last updated at Posted at 2017-10-11

ionic2で家計簿アプリを作ってます。
https://qiita.com/irohamaru/items/3df901cd7e12e3c85e9a

今回、カレンダーを実装したのですが、つまったポイントなどをまとめました。

ionic2-date-picker

今回使ったのはionic2-date-pickerというコンポーネント。

ionic2-date-picker
https://www.npmjs.com/package/ionic2-date-picker

スクリーンショット 2017-10-11 21.23.01.png

とりあえず組み込んでみる

自分のアプリに組み込んでみます。

カレントディレクトリを自分のアプリ(node_modulesが配置されているディレクトリ)にした後、以下のとおりインストール実行。

$ npm install -g ionic-date-picker --save

組み込み方は先ほどのページに書いてあるとおりです。
ボタン押下後、メソッド「showCalendar」でカレンダーを呼び出す場合の実装方法について書かれてます。

日付選択でカレンダーを閉じるようにする

デフォルトの仕様だと、「Cancel」または「OK」ボタンを押した後でないとカレンダーは閉じないようになっています。
今回、日付選択した後にカレンダーを閉じるようにしたいので、ちょっと改造します。

以下のjsを修正します。
jsに記述された「Component」の部分で、キャンセル、OKボタンのタグが記述してある部分を消すだけです。

[アプリ名]/node_modules/ionic-date-picker/date-picker.esm.js

中略

DatePicker = DatePicker_1 = __decorate([
    Component({

省略
// ↓を消す
\n    <button ion-button style=\"color:grey\" clear (click)=\"cancel()\">Cancel</button>\n    <button ion-button clear (click)=\"confirmDateSelection()\">OK</button>\n  </div>\n\n\n</div>

日付選択でカレンダーを閉じるために、日付選択時のメソッド「selectDate」を修正します。

キャンセル、OKボタン押下時に実行されるthis.viewCtrl.dismiss()を追加しますが、閉じた後の画面に日付のパラメータを引き渡したいので、引数に「this.selectedDateItem.momentDate.toDate()」を入れます。

date-picker.esm.js
    DatePicker.prototype.selectDate = function (day) {
        if (!day.isEnabled)
            return;
        if (this.selectedDateItem && this.selectedDateItem.isSelected) {
            this.selectedDateItem.isSelected = false;
        }
        day.isSelected = true;
        this.selectedDateItem = day;
        this.currentMoment = day.momentDate.clone();

        // ↓を追加
        this.viewCtrl.dismiss(this.selectedDateItem.momentDate.toDate());
    };

引き渡された日付のパラメータは、

sample.ts
    this.datePicker.onDateSelected.subscribe(
      (date) => {
        this.param = date
      });

のように、カレンダーを閉じた後の画面で定義された変数に代入することで、画面に表示することができます。
(date) => ... のdateが、引き渡された日付のパラメータです。

※this.datePicker.onDateSelected.subscribe(...)の部分は、ionic2-date-pickerの実装サンプルに記載されているソースコードです。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2