7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Angular: ngx-toastr でダイアログをトースト表示(Angular7対応)

Last updated at Posted at 2018-12-03

はじめに

これまで、エラーやメッセージのダイアログをalert("送信完了しました。")といった形で画面にメッセージを表示していたのですが、毎回消すのがめんどくさいしダサいので、自動で消え、かつ見た目もかっこよく、ということでトースト表示を実装してみました。
調べてみたらトースト表示が簡単に可能なライブラリはたくさんありましたが、今回は一番ダウンロード数とStar数の多かったngx-toastrを使ってみました。

(2019-03-12 追記)
Angular 7.2.8 にアップデートしたところ、トースターが急に表示されなくなりました。
こちらにあるように、bootstrapのcssクラス名とバッティングしてしまうことが原因のようで、私の環境ではstyles.scssにトースターの透明度を1に指定すると表示されるようになりました。

styles.scss
# toast-container > div {
    opacity:1;
}

実行画面

実際に動かしてみると以下のような動きになります。
ソースコードはこちら
angular-toaster.mov.gif

デモページも用意されており、見てみるとかなり細かい設定が可能なことが分かるかと思います。

動作環境

今回の動作環境は以下の通りです。最新バージョン(2018/12現在)でインストールしています。

Angular ngx-toastr
7.0.7 9.1.1
公式ページに載っているのは、以下の通りですので、Angular4系と5系をお使いの方はバージョン指定のインストールが必要かもしれません。
Angular ngx-toastr
4.x 6.4.1-beta.0
5.x 8.10.2

初期設定

設定方法ですが、公式ページにかなり詳しく載っていますが、一応ここでも簡単に触れたいと思います。

1. ngx-toastr本体のインストール

npm install ngx-toastr --save

2. @angular/animationsのインストール(インストール済みの場合は不要)

まずpackage.jsonを確認し、@angular/animationsが未インストールの場合のみ以下を実行してください。

npm install @angular/animations --save

3. CSSファイルの読み込み設定

以下の通り、Angular6(Angular CLI v6)以降の方はangular.jsonに、Angular5(Angular CLI v1.7)以前の方は.angular-cli.jsonにngx-toastrのcssファイル読み込み設定を行います。

angular.json(Angular6以降の方)
"styles": [
  "styles.scss",
  "node_modules/ngx-toastr/toastr.css"
]
.angular-cli.json(Angular5以前の方)
"styles": [
  "styles.scss",
  "../node_modules/ngx-toastr/toastr.css"    // 頭に「../」が必要
]

4. module.tsの設定

お使いのapp.module.ts(サブモージュールをお使いの方はそちら)に以下の設定を行います。

app.module.ts
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';    // add
 
import { ToastrModule } from 'ngx-toastr';    // add
 
@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule,    // add
    ToastrModule.forRoot()    // add
  ],
  bootstrap: [App],
  declarations: [App]
})
class AppModule {}

以上で初期設定は終わりです。

使い方

以下のように、this.toastrサービス.タイプ('メッセージ', 'タイトル', オプション)の形で呼び出せば、トースターが表示されます。
この例では、エラーダイアログのみ自動消去なし等の設定を行なっています。

app.component.ts
import { Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';    // add

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ngx-toastr';

  constructor(
    private toastr: ToastrService    // add
  ) {}


  showSuccess() {
    this.toastr.success('Hello world!', 'Toastr fun!');
  }
  showError() {
    const config = {
      closeButton: true,
      disableTimeOut: true,
      tapToDismiss: false
    };
    this.toastr.error('This is error message. Fix me!', 'Error', config);
  }
  showWarning() {
    this.toastr.warning('Warning!', 'Warning');
  }
  showInfo() {
    this.toastr.info('Info message.');
  }
}
app.component.html
  <button class="btn btn-primary" type="button" (click)="showSuccess()"> Success </button>
  <button class="btn btn-danger" type="button" (click)="showError()"> Error </button>
  <button class="btn btn-warning" type="button" (click)="showWarning()"> Warning </button>
  <button class="btn btn-info" type="button" (click)="showInfo()"> Info </button>

グローバル設定

全てのトースト表示に共通した設定を行いたい場合、app.module.tsにグローバル設定が可能です。

app.module.ts
imports: [
    CommonModule,
    BrowserAnimationsModule,
    // Toastr Global Settings
    ToastrModule.forRoot({
      timeOut: 2500,
      positionClass: 'toast-top-right',
      preventDuplicates: false
    })
  ],

さいごに

その他、細かい設定方法は公式ページをご参考ください。

参考

ngx-toastr

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?