R004: Angular 2x Toaster Implementation
Demo: github
- Through npm install Toaster
npm install toastr --save
- Include
toastr.min.js
andtoaster.min.css
in index file<link rel="stylesheet" href="node_modules/toastr/build/toastr.min.css"> <script src="node_modules/toastr/build/toastr.min.js"></script>
Create Toaster Service
import { Injectable } from '@angular/core' declare let toastr: any; @Injectable() export class ToastrService { success(message: string, title?: string) { toastr.success(message, title); } info(message: string, title?: string) { toastr.info(message, title); } warning(message: string, title?: string) { toastr.warning(message, title); } error(message: string, title?: string) { toastr.error(message, title); } }
- Inject in angular module file.
app.module.ts
... import { ToastrService } from './common/toastr.service'; @NgModule({ ... providers: [ToastrService], ... }) export class AppModule { }
Use Toastr
... import { ToastrService } from '../common/toastr.service'; @Component({ selector: 'events-list', template: ` <div> <event-thumbnail *ngFor="let event of events" (click)="handleThumbnailClick(event)" [event]="event"></event-thumbnail> </div> ` }) export class EventsListComponent implements OnInit { constructor(private toastr: ToastrService) { } handleThumbnailClick(event){ this.toastr.success(event.name); } ... };