Home > Software design >  Angular bootstrap alerts from service
Angular bootstrap alerts from service

Time:12-01

I am having a service, that listens to incoming events. If such an event happens, I want to notify the user. At the moment, I am using alert().

I want that, in every component, if the service triggers, a Bootstrap-alert pop-ups.

Is there anything to do that? (I am also using prime-ng, if there is something for that but no material)

So what I really want is kind of an "custom alert", and whenever I call the alertService.alert(string) a pop up appears.

CodePudding user response:

You can simply implement ngx-toastr npm package.

Then, use global styles for Bootstrap as written in the documentation:

// bootstrap style toast
// or import a bootstrap 4 alert styled design (SASS ONLY)
// should be after your bootstrap imports, it uses bs4 variables, mixins, functions
@import 'ngx-toastr/toastr-bs4-alert';
// if you'd like to use it without importing all of bootstrap it requires
@import 'bootstrap/scss/functions';
@import 'bootstrap/scss/variables';
@import 'bootstrap/scss/mixins';
// bootstrap 4
@import 'ngx-toastr/toastr-bs4-alert';
// boostrap 5
@import 'ngx-toastr/toastr-bs5-alert';

After importing ToastrModule and ToastrService (see the doc), It will be very easy to use:

this.toastrService.error('everything is broken', 'Major Error', {
  timeOut: 3000,
});

Also, you can use Angular Bootstrap Toast, It's a little more difficult and you have to write more code. But it's more customizable.

You can see Toast management service example to use Bootstrap Toast as service.

  • Related