UNPKG

13.9 kBMarkdownView Raw
1<div align="center">
2 <img src="https://raw.githubusercontent.com/scttcper/ngx-toastr/master/misc/documentation-assets/ngx-toastr-example.png" width="300" alt="Angular Toastr">
3 <br>
4 <h1>ngx-toastr</h1>
5 <br>
6 <a href="https://www.npmjs.org/package/ngx-toastr">
7 <img src="https://badge.fury.io/js/ngx-toastr.svg" alt="npm">
8 </a>
9 <a href="https://circleci.com/gh/scttcper/ngx-toastr">
10 <img src="https://circleci.com/gh/scttcper/ngx-toastr.svg?style=svg" alt="circleci">
11 </a>
12 <a href="https://codecov.io/github/scttcper/ngx-toastr">
13 <img src="https://img.shields.io/codecov/c/github/scttcper/ngx-toastr.svg" alt="codecov">
14 </a>
15 <br>
16 <br>
17</div>
18
19DEMO: https://ngx-toastr.vercel.app
20
21## Features
22
23- Toast Component Injection without being passed `ViewContainerRef`
24- No use of `*ngFor`. Fewer dirty checks and higher performance.
25- AoT compilation and lazy loading compatible
26- Component inheritance for custom toasts
27- SystemJS/UMD rollup bundle
28- Animations using Angular's
29 [Web Animations API](https://angular.io/docs/ts/latest/guide/animations.html)
30- Output toasts to an optional target directive
31
32## Dependencies
33
34Latest version available for each version of Angular
35
36| ngx-toastr | Angular |
37| ---------- | ----------- |
38| 11.3.3 | 8.x |
39| 12.1.0 | 9.x |
40| 13.2.1 | 10.x 11.x |
41| 14.3.0 | 12.x 13.x |
42| current | >= 14.x |
43
44## Install
45
46```bash
47npm install ngx-toastr --save
48```
49
50`@angular/animations` package is a required dependency for the default toast
51
52```bash
53npm install @angular/animations --save
54```
55
56Don't want to use `@angular/animations`? See
57[Setup Without Animations](#setup-without-animations).
58
59## Setup
60
61**step 1:** add css
62
63- copy
64 [toast css](/src/lib/toastr.css)
65 to your project.
66- If you are using sass you can import the css.
67
68```scss
69// regular style toast
70@import '~ngx-toastr/toastr';
71
72// bootstrap style toast
73// or import a bootstrap 4 alert styled design (SASS ONLY)
74// should be after your bootstrap imports, it uses bs4 variables, mixins, functions
75@import '~ngx-toastr/toastr-bs4-alert';
76
77// if you'd like to use it without importing all of bootstrap it requires
78@import '~bootstrap/scss/functions';
79@import '~bootstrap/scss/variables';
80@import '~bootstrap/scss/mixins';
81@import '~ngx-toastr/toastr-bs4-alert';
82```
83
84- If you are using angular-cli you can add it to your angular.json
85
86```ts
87"styles": [
88 "styles.scss",
89 "node_modules/ngx-toastr/toastr.css" // try adding '../' if you're using angular cli before 6
90]
91```
92
93**step 2:** add ToastrModule to app NgModule, make sure you have BrowserAnimationsModule as well
94
95```typescript
96import { CommonModule } from '@angular/common';
97import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
98
99import { ToastrModule } from 'ngx-toastr';
100
101@NgModule({
102 imports: [
103 CommonModule,
104 BrowserAnimationsModule, // required animations module
105 ToastrModule.forRoot(), // ToastrModule added
106 ],
107 bootstrap: [App],
108 declarations: [App],
109})
110class MainModule {}
111```
112
113## Use
114
115```typescript
116import { ToastrService } from 'ngx-toastr';
117
118@Component({...})
119export class YourComponent {
120 constructor(private toastr: ToastrService) {}
121
122 showSuccess() {
123 this.toastr.success('Hello world!', 'Toastr fun!');
124 }
125}
126```
127
128## Options
129
130There are **individual options** and **global options**.
131
132### Individual Options
133
134Passed to `ToastrService.success/error/warning/info/show()`
135
136| Option | Type | Default | Description
137| ----------------- | ------------------------------ | ------------------------------ | ------------------------------------------------- |
138| toastComponent | Component | Toast | Angular component that will be used |
139| closeButton | boolean | false | Show close button |
140| timeOut | number | 5000 | Time to live in milliseconds |
141| extendedTimeOut | number | 1000 | Time to close after a user hovers over toast |
142| disableTimeOut | `boolean \| 'timeOut' \| 'extendedTimeOut'` | false | Disable both timeOut and extendedTimeOut when set to `true`. Allows specifying which timeOut to disable, either: `timeOut` or `extendedTimeOut` |
143| easing | string | 'ease-in' | Toast component easing |
144| easeTime | string \| number | 300 | Time spent easing |
145| enableHtml | boolean | false | Allow html in message |
146| progressBar | boolean | false | Show progress bar |
147| progressAnimation | `'decreasing' \| 'increasing'` | 'decreasing' | Changes the animation of the progress bar. |
148| toastClass | string | 'ngx-toastr' | Class on toast |
149| positionClass | string | 'toast-top-right' | Class on toast container |
150| titleClass | string | 'toast-title' | Class inside toast on title |
151| messageClass | string | 'toast-message' | Class inside toast on message |
152| tapToDismiss | boolean | true | Close on click |
153| onActivateTick | boolean | false | Fires `changeDetectorRef.detectChanges()` when activated. Helps show toast from asynchronous events outside of Angular's change detection |
154
155#### Setting Individual Options
156
157success, error, info, warning take `(message, title, ToastConfig)` pass an
158options object to replace any default option.
159
160```typescript
161this.toastrService.error('everything is broken', 'Major Error', {
162 timeOut: 3000,
163});
164```
165
166### Global Options
167
168All [individual options](#individual-options) can be overridden in the global
169options to affect all toasts. In addition, global options include the following
170options:
171
172| Option | Type | Default | Description |
173| ----------------------- | ------- | ---------------------------------- | ------------------------------------------------------------------ |
174| maxOpened | number | 0 | Max toasts opened. Toasts will be queued. 0 is unlimited |
175| autoDismiss | boolean | false | Dismiss current toast when max is reached |
176| iconClasses | object | [see below](#iconclasses-defaults) | Classes used on toastr service methods |
177| newestOnTop | boolean | true | New toast placement |
178| preventDuplicates | boolean | false | Block duplicate messages |
179| countDuplicates | boolean | false | Displays a duplicates counter (preventDuplicates must be true). Toast must have a title and duplicate message |
180| resetTimeoutOnDuplicate | boolean | false | Reset toast timeout on duplicate (preventDuplicates must be true) |
181| includeTitleDuplicates | boolean | false | Include the title of a toast when checking for duplicates (by default only message is compared) |
182
183##### iconClasses defaults
184
185```typescript
186iconClasses = {
187 error: 'toast-error',
188 info: 'toast-info',
189 success: 'toast-success',
190 warning: 'toast-warning',
191};
192```
193
194#### Setting Global Options
195
196Pass values to `ToastrModule.forRoot()`
197
198```typescript
199// root app NgModule
200imports: [
201 ToastrModule.forRoot({
202 timeOut: 10000,
203 positionClass: 'toast-bottom-right',
204 preventDuplicates: true,
205 }),
206],
207```
208
209### Toastr Service methods return:
210
211```typescript
212export interface ActiveToast {
213 /** Your Toast ID. Use this to close it individually */
214 toastId: number;
215 /** the title of your toast. Stored to prevent duplicates if includeTitleDuplicates set */
216 title: string;
217 /** the message of your toast. Stored to prevent duplicates */
218 message: string;
219 /** a reference to the component see portal.ts */
220 portal: ComponentRef<any>;
221 /** a reference to your toast */
222 toastRef: ToastRef<any>;
223 /** triggered when toast is active */
224 onShown: Observable<any>;
225 /** triggered when toast is destroyed */
226 onHidden: Observable<any>;
227 /** triggered on toast click */
228 onTap: Observable<any>;
229 /** available for your use in custom toast */
230 onAction: Observable<any>;
231}
232```
233
234### Put toasts in your own container
235
236Put toasts in a specific div inside your application. This should probably be
237somewhere that doesn't get deleted. Add `ToastContainerModule` to the ngModule
238where you need the directive available. Make sure that your container has
239an `aria-live="polite"` attribute, so that any time a toast is injected into
240the container it is announced by screen readers.
241
242```typescript
243import { BrowserModule } from '@angular/platform-browser';
244import { NgModule } from '@angular/core';
245import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
246
247import { ToastrModule, ToastContainerModule } from 'ngx-toastr';
248
249import { AppComponent } from './app.component';
250
251@NgModule({
252 declarations: [AppComponent],
253 imports: [
254 BrowserModule,
255 BrowserAnimationsModule,
256
257 ToastrModule.forRoot({ positionClass: 'inline' }),
258 ToastContainerModule,
259 ],
260 providers: [],
261 bootstrap: [AppComponent],
262})
263export class AppModule {}
264```
265
266Add a div with `toastContainer` directive on it.
267
268```typescript
269import { Component, OnInit, ViewChild } from '@angular/core';
270
271import { ToastContainerDirective, ToastrService } from 'ngx-toastr';
272
273@Component({
274 selector: 'app-root',
275 template: `
276 <h1><a (click)="onClick()">Click</a></h1>
277 <div aria-live="polite" toastContainer></div>
278 `,
279})
280export class AppComponent implements OnInit {
281 @ViewChild(ToastContainerDirective, { static: true })
282 toastContainer: ToastContainerDirective;
283
284 constructor(private toastrService: ToastrService) {}
285 ngOnInit() {
286 this.toastrService.overlayContainer = this.toastContainer;
287 }
288 onClick() {
289 this.toastrService.success('in div');
290 }
291}
292```
293
294## Functions
295
296##### Clear
297
298Remove all or a single toast by optional id
299
300```ts
301toastrService.clear(toastId?: number);
302```
303
304##### Remove
305
306Remove and destroy a single toast by id
307
308```
309toastrService.remove(toastId: number);
310```
311
312## SystemJS
313
314If you are using SystemJS, you should also adjust your configuration to point to
315the UMD bundle.
316
317In your SystemJS config file, `map` needs to tell the System loader where to
318look for `ngx-toastr`:
319
320```js
321map: {
322 'ngx-toastr': 'node_modules/ngx-toastr/bundles/ngx-toastr.umd.min.js',
323}
324```
325
326## Setup Without Animations
327
328If you do not want to include `@angular/animations` in your project you can
329override the default toast component in the global config to use
330`ToastNoAnimation` instead of the default one.
331
332In your main module (ex: `app.module.ts`)
333
334```typescript
335import { ToastrModule, ToastNoAnimation, ToastNoAnimationModule } from 'ngx-toastr';
336
337@NgModule({
338 imports: [
339 // ...
340
341 // BrowserAnimationsModule no longer required
342 ToastNoAnimationModule.forRoot(),
343 ],
344 // ...
345})
346class AppModule {}
347```
348
349That's it! Animations are no longer required.
350
351## Using A Custom Toast
352
353Create your toast component extending Toast see the demo's pink toast for an example
354https://github.com/scttcper/ngx-toastr/blob/master/src/app/pink.toast.ts
355
356```typescript
357import { ToastrModule } from 'ngx-toastr';
358
359@NgModule({
360 imports: [
361 ToastrModule.forRoot({
362 toastComponent: YourToastComponent, // added custom toast!
363 }),
364 ],
365 bootstrap: [App],
366 declarations: [App, YourToastComponent], // add!
367})
368class AppModule {}
369```
370
371## FAQ
372
3731. ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it
374 was checked\
375 When opening a toast inside an angular lifecycle wrap it in setTimeout
376
377```typescript
378ngOnInit() {
379 setTimeout(() => this.toastr.success('sup'))
380}
381```
382
3832. Change default icons (check, warning sign, etc)\
384 Overwrite the css background-image https://github.com/scttcper/ngx-toastr/blob/master/src/lib/toastr.css
3853. How do I use this in an ErrorHandler? See:
386 https://github.com/scttcper/ngx-toastr/issues/179
3874. How can I translate messages See:
388 https://github.com/scttcper/ngx-toastr/issues/201
3895. How to handle toastr click/tap action?
390
391```ts
392showToaster() {
393 this.toastr.success('Hello world!', 'Toastr fun!')
394 .onTap
395 .pipe(take(1))
396 .subscribe(() => this.toasterClickedHandler());
397}
398
399toasterClickedHandler() {
400 console.log('Toastr clicked');
401}
402```
403
404## Previous Works
405
406[toastr](https://github.com/CodeSeven/toastr) original toastr\
407[angular-toastr](https://github.com/Foxandxss/angular-toastr) AngularJS toastr\
408[notyf](https://github.com/caroso1222/notyf) notyf (css)
409
410## License
411
412MIT
413
414---
415
416> GitHub [@scttcper](https://github.com/scttcper) &nbsp;&middot;&nbsp;
417> Twitter [@scttcper](https://twitter.com/scttcper)