ons-alert-dialog

現在のスクリーンの上に表示するアラートダイアログです。ユーザに対する問いかけ、警告、エラーメッセージを表示するのに利用できます。タイトルやコンテンツやボタンは簡単にカスタマイズでき、実行しているプラットフォームに併せてスタイルが自動的に切り替わります。

実例

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関数を終了時に呼び出すことを忘れないでください。

関連情報

名前 型 / デフォルト値 概要
modifier String ダイアログの見た目を指定します。 Optional.
cancelable この属性を設定すると、ダイアログの背景をタップしたりAndroidデバイスのバックボタンを押すとダイアログが閉じるようになります。 Optional.
disabled この属性がある時、アラートダイアログはdisabled状態になります。 Optional.
animation String
default
ダイアログを表示する際のアニメーション名を指定します。デフォルトでは”none”か”default”が指定できます。 Optional.
animation-options Expression アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。例:{duration: 0.2, delay: 1, timing: ‘ease-in’} Optional.
mask-color String
rgba(0, 0, 0, 0.2)
背景のマスクの色を指定します。”rgba(0, 0, 0, 0.2)”がデフォルト値です。 Optional.
visible Boolean 要素が見える場合にtrue。 Optional.
名前 概要
disabled 無効化されている場合にtrue。
cancelable そのダイアログがキャンセル可能かどうかを表します。キャンセル可能なダイアログは、背景をタップするかAndroidデバイスのバックボタンを押すことで閉じることが出来るようになります。
maskColor 背景のマスクの色を指定します。”rgba(0, 0, 0, 0.2)”がデフォルト値です。
visible 要素が見える場合にtrue。
onDeviceBackButton バックボタンハンドラ。
animationOptions アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。例:{duration: 0.2, delay: 1, timing: ‘ease-in’}
Name 概要
material マテリアルデザインのスタイル
rowfooter フッターの複数のボタンを水平に配置
シグネチャ 概要
show([options]) ダイアログを表示します。
hide([options]) ダイアログを閉じます。
show([options]): Promise

ダイアログを表示します。

返り値: 表示される要素を解決するPromiseオブジェクトを返します。

パラメーター
名前 型 概要
options Object オプションを指定するオブジェクトです。
options.animation String アニメーション名を指定します。指定できるのは、”fade”, “none”のいずれかです。
options.animationOptions String アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: ‘ease-in’}
options.callback Function ダイアログが表示され終わった時に呼び出されるコールバックを指定します。
hide([options]): Promise

ダイアログを閉じます。

返り値: 隠れた要素を解決するPromiseオブジェクトを返します。

パラメーター
名前 型 概要
options Object オプションを指定するオブジェクト。
options.animation String アニメーション名を指定します。”fade”, “none”のいずれかを指定します。
options.animationOptions String アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: ‘ease-in’}
options.callback Function このダイアログが閉じた時に呼び出されるコールバックを指定します。
名前 概要
preshow アラートダイアログが表示される直前に発火します。
postshow アラートダイアログが表示された直後に発火します。
prehide アラートダイアログが隠れる直前に発火します。
posthide アラートダイアログが隠れた後に発火します。
dialogcancel Fired when the dialog is canceled. (翻訳中)
preshow

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

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

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

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

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

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

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

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

Fired when the dialog is canceled. (翻訳中)

パラメーター
名前 型 概要

お困りですか?

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

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

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