35
How to add toastr module to Angular project
In any web application showing the alert or message to indicate the different status is required functionality to have which help to understand the users what is happening under the hood.
First, open the terminal and run the following command inside your project to install the ngx-toastr plugin
npm install ngx-toastr --save
Next, you need to install animation package which is required to toastr plugin.
npm install @angular/animations --save
Next open angular.json and add the following style which is required for toastr.
"styles": [
"src/styles.scss",
"node_modules/ngx-toastr/toastr.css"
],
Next open app.module.js file and import BrowserAnimationsModule and ToastrModule.
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
First, you should apply ToastrService to the component where you want to show the toastr. Also need to initiate through the constructer method. Then you can use different methods like success, warning, error based on your requirement.
import { ToastrService } from 'ngx-toastr';
export class LandingComponent implements OnInit {
constructor(private toastr:ToastrService) { }
ngOnInit(): void {
}
showToastr(){
this.toastr.success('This is the success toastr')
}
}
The first parameter of the method success accept the message and you can pass the title for the second parameter.
showToastr(){
this.toastr.success('This is the success toastr',"Success")
}
By default, toastr will appear in the right top corner. This can be changed by setting positionClass when importing the module.
ToastrModule.forRoot({
positionClass: 'toast-top-center'
})
If you click the button multiple times you can see a lot of toastrs appear on the screen. To prevent that you can disable the duplicates.
ToastrModule.forRoot({
preventDuplicates: true
})
ToastrModule.forRoot({
closeButton:true
})
Default toastr will disappear after 5 seconds. This can be changed by setting timeOut property. This accepts a value as milliseconds and makes sure to convert seconds to milliseconds before adding.
ToastrModule.forRoot({
timeOut:2000
})
If you want to show multiple toastrs and need to control the maximum numbers, maxOpened property will allow to do that.
ToastrModule.forRoot({
maxOpened:2
})
Previously we show the way of adding different config root levels which will affect all toastrs. But you can add those in toastr level if you required different configs for different places in the app.
showToastr(){
this.toastr.success('This is the success toastr',"Success")
this.toastr.error('This is the error toastr',"Error",{
timeOut:10000,
closeButton:true
})
}
35