Reputation: 1515
I have been reading up on this on the actual site for ngx-toastr ngx-toastr, and other posts on Stack Overflow, but cannot find a clear solution for my work case.
I am trying to change the position of the toastr
for specific use cases. Example; when it is an error, show the toastr
on the top.
I have a very vanilla setup.
In my app.module.ts
I have the following:
import { ToastrModule } from 'ngx-toastr';
In my imports of app.module.ts
I have:
imports: [
BrowserModule,
ToastrModule.forRoot({
timeOut: 3500,
positionClass: 'toast-bottom-center',
preventDuplicates: true,
}),
In my components I declare the toastr
in my constructor
:
constructor(private toastr: ToastrService) {}
And I use the toastr
as follows:
this.toastr.error('There was an error loading the Asset List!', 'Asset Register');
As per my setup, all toast show in 'toast-bottom-center'
. How can I modify this call to show the toast on the top?
this.toastr.error('There was an error loading the Asset List!', 'Asset Register');
Upvotes: 9
Views: 32567
Reputation: 729
The 3rd parameter of the error method is used to provide the position of the toastr message (among other things).
this.toastrService.error('There was an error loading the Asset List!', 'Asset Register');
this.toastrService.warning('Some warning message', 'some title', {
positionClass: 'toast-bottom-right'
});
Upvotes: 15
Reputation: 31
Add this in style.css
.toast-top-center {
bottom: 0;
margin: 0 auto;
right: 0;
left: 0;
width: 100%;
}
Insert this in your toast function
show(config: { type: string, title: string, subTitle?: string }): void {
switch (config.type) {
case 'Success':
this._toastr.success(config.subTitle ? config.subTitle : '', config.title,{ positionClass: 'toast-top-center'});
break;
case 'Error':
this._toastr.error(config.subTitle ? config.subTitle : '', config.title, { positionClass: 'toast-top-center'});
break;
case 'Warning':
this._toastr.warning(config.subTitle ? config.subTitle : '', config.title, { positionClass: 'toast-top-center'});
break;
case 'Info':
this._toastr.info(config.subTitle ? config.subTitle : '', config.title, { positionClass: 'toast-top-center'});
break;
default:
break;
}
}
Upvotes: 3
Reputation:
Make a service for that.
Start by creating an enum
export enum ToasterPosition {
topRight = 'toast-top-right',
topLeft = 'toast-top-left',
bottomRight = 'toast-bottom-right',
bottomLeft= 'toast-bottom-left',
// Other positions you would like
}
Now create your service
export class ToasterService {
constructor(private toastr: ToastrService) {}
public error(title: string, message: string, positionClass: ToasterPosition) {
this.toastr.error(message, title, { positionClass });
}
}
This way, you can't miss the positioning, since you have to provide an enum.
Upvotes: 10