ons-toast

実例

Dialog

Onsen UIではダイアログを表示する方法がいくつかあります。このチュートリアルでは次のダイアログの使い方を解説します。

  • onsNotification
  • ons-alert-dialogとAlertDialogFactory
  • ons-dialogとDialogFactory

onsNotification

onsNotificationは単純なアラートダイアログを表示することができます。onsNotificationの持つalert(), confirm(), prompt()メソッドの役割は、window.alert()やwindow.confirm()やwindow.prompt()と対応しています。

import onsNotification from 'angular2-onsenui';

// アラートを表示する
onsNotification.alert('Hello World!');

確認ダイアログを表示するには、onsNotification.confirm()を使います。

onsNotification.confirm({
  message: 'This dialog can be canceled by tapping the background or using the back button on your device.',
  cancelable: true,
  callback: i => {
    if (i == -1) {
      // canselされた場合iは-1が代入される
      onsNotification.alert({message: 'You canceled it!'});
    }
  }
});

プロンプトを表示するには、onsNotification.prompt()を用います。

onsNotification.prompt({
  message: 'What is the meaning of Life, the Universe and Everything?',
  callback: answer => {
    if (answer === '42') {
      onsNotification.alert({message: 'That\'s the correct answer!'});
    } else {
      onsNotification.alert({message: 'Incorrect! Please try again!'});
    }
  }
});

onsNotificationはons.notificationのラッパーです。APIの詳細は、ons.notificationのリファレンスを参照してください。

<ons-alert-dialog>とAlertDialogFactory

単純なアラートダイアログではなく、振る舞いやコンテンツをカスタマイズしたい場合には、<ons-alert-dialog>要素とAlertDialogFactoryを利用します。

onsNotificationの場合とは違って、Angular 2アプリケーション下で<ons-alert-dialog>要素を使うには手順が必要です。まず、<ons-alert-dialog>を使ってComponentを宣言します。

@Component({
  template: `
    <ons-alert-dialog cancelable #alert>
      <div class="alert-dialog-title">Warning!</div>
      <div class="alert-dialog-content">
        Hello World!
      </div>
      <div class="alert-dialog-footer">
        <button class="alert-dialog-button" (click)="alert.hide()">OK</button>
      </div>
    </ons-alert-dialog>
  `
})
class MyAlertDialogComponent {
}

次にこのコンポーネントとして呼び出すにはAlertDialogFactoryを使います。AlertDialogFactoryオブジェクトは次のようにコンポーネントのコンストラクタの引数に指定することでAngular 2のDIを通じて取得することができます。

@Component({
  'selector': 'app',
  'template': '<div></div>'
})
export class AppComponent {
  constructor(adf: AlertDialogFactory) {
  }
}

AlertDialogFactoryは、<ons-alert-dialog>を使っているコンポーネントを動的に生成することができます。初期化時にダイアログを生成したい場合には、次のようにコンポーネントのngAfterViewInit()内でcreateAlertDialog()メソッドを使ってください。

また、一度作成したアラートダイアログはdestroy関数で必ず消して下さい。ドキュメントのDOMツリーの中に保持されし続けるので、DOMリークを引き起こします。

export class AppComponent implements AfterViewInit, OnDestroy {
  private _alert: any;
  private _destroyAlert: Function;

  constructor(private _adf: AlertDialogFactory) {
  }

  ngAfterViewInit() {
    this._adf
      .createAlertDialog(MyAlertDialogComponent, {message: 'This is just an example.'})
      .then(({alertDialog, destroy}) => {
        this._alert = alertDialog;
        this._alert.show();
        this._destroyAlert = destroy;
      });
  }

  ngOnDestroy() {
    this._destroyAlert();
  }
}

ビューの初期化が行われていないconstructor()内でcreateAlertDialog()を呼び出すとエラーを引き起こすことに注意してください。

パラメータを受け取る

createAlertDialog()の第二引数には、任意のデータを渡すことができます。

this._adf
  .createAlertDialog(MyAlertDialogComponent, {message: 'This is just an example.'})
  .then(({alertDialog, destroy}) => {
    // ...
  });

ここで渡したデータは、AlertDialogのコンポーネントのコンストラクタから取得することができます。

class MyAlertDialogComponent {
  message = '';

  constructor(params: Params) {
    this.message = <string>params.at('message');
  }
}

NgModule

AlertDialogFactoryで読み込むコンポーネントは動的に読み込まれるものであるため、NgModuleのdeclarationsとentryComponentsに追加することを忘れないでください。

@NgModule({
  imports: [OnsenModule],
  declarations: [AppComponent, MyAlertDialogComponent],
  bootstrap: [AppComponent],
  entryComponents: [MyAlertDialogComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class AppModule { }

<ons-dialog>とDialogFactory

アラートダイアログではなく、<ons-page>や<ons-navigator>などを埋め込めるダイアログを表示する場合には、<ons-dialog>を使います。

<ons-dialog>をAngular 2で生成するには、DialogFactoryを使います。先ほど紹介したAlertDialogFactoryとほとんど同じ方法で使うことができます。

@Component({
  template: `
    <ons-dialog #dialog>
      <div class="dialog-mask"></div>
      <div class="dialog">
        <div class="dialog-container" style="height: 200px;">
          <ons-page>
            <ons-toolbar>
              <div class="center">Name</div>
            </ons-toolbar>
            <div class="content">
              <div style="text-align: center">
                <p>{{message}}</p>
                <br>
                <ons-button (click)="dialog.hide()">Close</ons-button>
              </div>
            </div>
          </ons-page>
        </div>
      </div>
    </ons-dialog>
  `
})
class MyDialogComponent {
  message = '';

  constructor(params: Params) {
    this.message = <string>params.at('message');
  }
}

DialogFactoryを通じてこのMyDialogComponentを初期化します。

export class AppComponent implements AfterViewInit, OnDestroy {
  private _dialog: any;
  private _destroyDialog: Function;

  constructor(private _df: DialogFactory) {
  }

  ngAfterViewInit() {
    this._df
      .createDialog(MyDialogComponent, {message: 'This is just an example.'})
      .then(({dialog, destroy}) => {
        this._dialog = dialog;
        this._destroyDialog = destroy;
      });
  }

  ngOnDestroy() {
    this._destroyDialog();
  }
}

AlertDialogの場合と同様に、初期化時に渡されるdestroy関数を終了時に呼び出すことを忘れないでください。

関連情報

名前 型 / デフォルト値 概要
animation String
default
The animation used when showing and hiding the toast. Can be either "default", "ascend" (Android), "lift" (iOS), "fall", "fade" or "none". (翻訳中) Optional.
animation-options Expression アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. {duration: 0.2, delay: 1, timing: ‘ease-in’} Optional.
visible Boolean 要素が見える場合にtrue。 Optional.
名前 概要
animationOptions アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。例:{duration: 0.2, delay: 1, timing: ‘ease-in’}
onDeviceBackButton バックボタンハンドラ。
visible 要素が見える場合にtrue。
シグネチャ 概要
show([options]) Show the element. (翻訳中)
toggle([options]) Toggle toast visibility. (翻訳中)
hide([options]) Hide toast. (翻訳中)
show([options]): Promise

Show the element. (翻訳中)

返り値:

パラメーター
名前 型 概要
options Object オプションを指定するオブジェクト。
options.animation String Animation name. Available animations are "default", "ascend" (Android), "lift" (iOS), "fall", "fade" or "none". (翻訳中)
options.animationOptions String アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: ‘ease-in’}
toggle([options])

Toggle toast visibility. (翻訳中)

パラメーター
名前 型 概要
options Object オプションを指定するオブジェクト。
options.animation String Animation name. Available animations are "default", "ascend" (Android), "lift" (iOS), "fall", "fade" or "none". (翻訳中)
options.animationOptions String アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: ‘ease-in’}
hide([options]): Promise

Hide toast. (翻訳中)

返り値:

パラメーター
名前 型 概要
options Object オプションを指定するオブジェクト。
options.animation String Animation name. Available animations are "default", "ascend" (Android), "lift" (iOS), "fall", "fade" or "none". (翻訳中)
options.animationOptions String アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: ‘ease-in’}
名前 概要
preshow ダイアログが表示される直前に発火します。
postshow ダイアログが表示された直後に発火します。
prehide ダイアログが隠れる直前に発火します。
posthide ダイアログが隠れた後に発火します。
preshow

ダイアログが表示される直前に発火します。

パラメーター
名前 型 概要
event Object Event object.
event.toast Object ダイアログのオブジェクト。
event.cancel Function この関数を実行すると、ダイアログの表示を止めます。
postshow

ダイアログが表示された直後に発火します。

パラメーター
名前 型 概要
event Object Event object.
event.toast Object ダイアログのオブジェクト。
prehide

ダイアログが隠れる直前に発火します。

パラメーター
名前 型 概要
event Object Event object.
event.toast Object ダイアログのオブジェクト。
event.cancel Function この関数を実行すると、ダイアログが閉じようとするのを止めます。
posthide

ダイアログが隠れた後に発火します。

パラメーター
名前 型 概要
event Object Event object.
event.toast Object ダイアログのオブジェクト。

お困りですか?

Onsen UIに関する質問は、Stack Overflowにてonsen-uiタグを付与してください。Onsen UIチームはあなたの問題解決をお手伝いします。

バグ報告や機能要望については、GitHub Issuesに記載をお願いいたします。

あわせて、下記の情報も参考にしてください。