Our approach involved creating a specialized container within the AppComponent
, allowing for easy reuse by other components.
To begin, we established a custom container in the template, similar to the instructions outlined in the documentation. It's worth noting that as of the current date (2023-11-14), there have been some updates; instead of importing ToastContainerModule
, you now import ToastContainerDirective
as a standalone entity, either within a separate component or within the relevant module (such as our use of AppModule
):
Within AppModule
, we include:
imports: [
BrowserAnimationsModule,
// ...
ToastrModule.forRoot(),
ToastContainerDirective
],
And within the app.component.html
template:
<!-- custom toastr container -->
<div toastContainer aria-live="polite"></div>
<router-outlet> ... </router-outlet>
A key divergence from the documentation is that we opt not to set { positionClass: 'inline' }
as a global parameter during module import. Instead, we configure different components and options tailored to specific scenarios while retaining the default overlay setting.
In order to employ the custom-inline container (alongside others) across various components, all configurations are centralized within a service like CustomToastrService. Any adjustments to layouts necessitate custom components as well.
Within the service, methods can be defined to handle varying option combinations and utilize custom components based on requirements:
export type ToastOptions = {msg: string; type: 'error'|'success'|...; title?: string; ...};
@Injectable({providedIn:'root'})
export class CustomToastrService {
constructor(private toastrService: ToastrService) {
//...
}
/* Show a toastr inline */
public showInlineToastr(options: ToastOptions) {
const toastOptions = {
toastClass: `ngx-toastr toast-${options.type}`,
positionClass: 'inline',
// ... more options
};
this.toastrService.show(options.msg, options.title, toastOptions);
}
/* Display a toast as an overlay at the top in full-width */
public showToast(options: ToastOptions) {
const toastOptions = {
toastClass: `ngx-toastr toast-${options.type}`,
positionClass: 'toast-top-full-width',
// ... more options
};
this.toastrService.show(options.msg, options.title, toastOptions);
}
// Utilize a custom component
public showCustomToast(options: ToastOptions) {
const toastOptions = {
toastClass: '', // set in template
toastComponent: CustomToastComponent,
// ...
};
this.toastrService.show(options.msg, options.title, toastOptions);
}
}