Put the Toastr notifications inside a designated container within a particular component

Toastify allows you to set a global container for displaying toasts using the following method:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ToastrModule, ToastContainerModule } from 'ngx-toastr';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,

    ToastrModule.forRoot({ positionClass: 'inline' }), // <-- this
    ToastContainerModule,                              // <-- lines
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

I am interested in achieving a similar setup but I only want to display these toasts within a specific container in one component without affecting toasts in other parts of the application. This is strictly for one component and not related to any module or route.

Is it possible to achieve this kind of functionality?

Answer №1

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);
  }    
}

Answer №2

When utilizing a toastr, you have the ability to implement configurations at the same time. Take a look at the example provided:

this.toastr.success('Textt', 'Text2', {
  positionClass: 'top-right',
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application. While ngrx all ...

Accommodate the Angular form with a null value

In my form initialization method, I am encountering an issue when there is no email value coming from the API. This results in the error message: ERROR TypeError: Cannot read property 'value' of undefined private initForm() { this._userSer ...

"Dealing with Angular 9's mat-table and the pesky ExpressionChangedAfterItHasBeenChecked

I am facing an issue with my Angular 9 component that has multiple mat-tables. One of the tables contains rows with input fields bound to a reactive form array. While binding the table to the form array works well, I encounter an error when loading the for ...

What could be causing jQuery to overlook this button?

Having some trouble with my angular, bootstrap, and jQuery setup. I can't get jQuery to select a button and trigger an alert when clicked: $('#some_button').click(function(e) { alert('testing'); }); <button id="some_but ...

Tips on Identifying the Category

I am currently studying TypeScript. Recently, I have been using Axios to fetch API data, and then I stored the returned value in a useEffect hook. However, when trying to display it on the screen, I encountered an error stating that there is no 'name ...

Guide on Validating Several Email Addresses in a React Form using Angular 4

I need to input 50 email addresses with the same domain name (gmail.com). Currently, I am using a Reactive form but the code I have implemented is not working as expected. https://stackblitz.com/edit/angular-wfwfow If anyone could assist me with this, I ...

Utilize the .mat-column-name attributes to apply custom styles to a nested component within Angular Material

Within the Child component, an Angular material table is created with columns passed as input: <table mat-table> <ng-container *ngFor="let col of columns" [matColumnDef]="col"> </table> @Input() columns: string[] T ...

What sets apart regular component styles from nested styles within the :host selector?

Here is an example of component-level styling for a component with the default view encapsulation value of ViewEncapsulation.Emulated: :host h2 { color: red; } When compiled, the CSS will look like this: [_nghost-c0] h2[_ngcontent-c0] { color: r ...

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

NextJS API Generator for OpenAPI specifications

In my NextJS project, we utilize the /api path to implement our API, with an openapi.yaml file defining the interface. To generate the API client successfully, we run the following command: openapi-generator-cli generate -i data/api/openapi.yaml -o src/api ...

Retrieving information from a data file by implementing a GraphQL Apollo Server within a NextJS application route

Currently working with Next.js 14 (app route), React, and the GraphQL Apollo framework. I have a JSON file containing data saved locally that I'd like to display using the server API. How can I make this happen? Below is the JSON structure I need to r ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Tips for managing unfinished transactions through Stripe

I have successfully set up a checkout session with Stripe and included a cancel_url as per the documentation. However, I am facing an issue where the cancel_url is only triggered when the user clicks the back button provided by Stripe. What I want to achie ...

Discovering all subclasses of a base class in AngularWould you like to learn how

abstract class Item { private name: string; private description: string; constructor(name: string,description:string) { this.name = name; this.description = description; } } class Car extends Item { constructor(name: string,descri ...

Is there a way to handle null return in case the data is not present?

Is there a way to handle situations where the data I pass is empty, like if(!testimonials) return null? Currently, it just shows an empty array. I'm not sure where to implement an "if-else" rule. AboutUs Page export const getServerSideProps = async ( ...

Troubleshooting Cors Problem between Angular 2 Form Data and Express

I'm attempting to send some files to an Express server that utilizes the cors() module in the following way app.use(cors()); This is the Angular 2 code used for file uploading let formData:FormData = new FormData(); for(let i = 0; i < files. ...

The service.subscribe function in Angular's Component Constructor is not functioning properly after the update

There are two components in my project, a parent and child component, and I am using a shared service to transfer data between them. The structure of the Service Class is as follows: export class AddItemDataTransferService { // Observable string sourc ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

When subscribing to an Observable of type number or string (union type), NaN values are returned for string inputs

Within a component, I have a public member that is defined as follows: public docId$: Observable<number | string>; This means that the document ID can either be an integer or a string. Upon initializing in ngOnInit, I have the following code snippe ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...