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

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Properly defining a DI service in Angular 2.1.2 using ES5

I have created an Angular 2 service that utilizes the Http service and is accessed by other components. However, I am unsure if my implementation is correct: (function (app) { 'use strict'; app.LoaderService = ng.core.Component({ providers: ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

import error causing an angular application to crash even with the module installed

Is there a possibility that an error is occurring with the import statement even though the syntax is correct and the required library has been installed? Could the issue lie within the core settings files, specifically the ones mentioned below (package.js ...

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

How can I properly format an Angular locale date for API consumption?

I am currently utilizing two-way binding within my template-driven form: ts: searchLeaveApplication: any = {}; html: <mat-form-field class="searchInputs"> <input matInput [matDatepicker]="searchStartDate" [(ngModel)]="this.search ...

Utilize localStorage.getItem() in conjunction with TypeScript to retrieve stored data

Within my codebase, I have the following line: const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal; Unexpectedly, Typescript triggers an alert with this message: Argument ...

Error: module not found in yarn

In my yarn workspace, I have organized folders named public and server. While working with TypeScript in VS Code, I encounter an error message stating: Cannot find module 'x' Interestingly, even though the error persists, IntelliSense suggests ...

Resize the textarea to fit a maximum of five lines, and display a scrollbar if necessary

Explanation: I am facing an issue in Angular 2 regarding the chat screen. I need the chat screen to dynamically increase in size as I type, up to a maximum of 5 lines, and then show a scrollbar. How can I achieve this functionality? Problem: The current b ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

The React-Typescript error message is stating that the module "react-router-dom" does not have the exported member "RouteComponentProps"

I encountered an issue with my project involving a login page and the usage of "RouteComponentProps". Unfortunately, I received the following error: Module '"react-router-dom"' has no exported member 'RouteComponentProps'. Upon attempt ...

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

Error: Unexpected input detected in `ts.resolveTypeReferenceDirective`. This issue may lead to a debug failure

I'm encountering the error below: { "name": "Angular", "version": "1.0.0", ... } If anyone has insights on what steps to take next or the potential cause of the problem, your input would be greatly a ...

What is the best approach to incorporate a stopwatch?

I'm exploring ways to track the time it takes for a user to click a button. While I have a working solution, I'm curious if there's a more efficient method available. Below is my current implementation: export class MainComponent implements ...

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 ...

The output from Angular Validator.pattern() may differ from that generated by online regex engines

Currently, I am facing an issue with my form group and a regular expression used to validate names. The criteria for the name input field are: It must be required. It should be alphanumeric. It must start with alphabets. It cannot contain any special char ...

How to effectively implement form-control with mat-radio-group?

UPDATE: Check out my code on stackblitz I'm facing an issue with my form layout. The form control rows are overlapping with the radio button rows. I need help to resolve this problem. Here is a snippet of my code: <form [formGroup]="formGroup" (n ...

When working with Nativescript Schematics, ensure that all necessary modules are loaded properly

Currently, I am attempting to implement code sharing between an Angular web application and a mobile app using NativeScript Schematics. Below is the structure of my code https://i.stack.imgur.com/xgNrs.png In the mobile-specific HTML file, I have utilize ...

Issue encountered during mozjpeg installation - unable to locate mozjpeg's cjpeg in the vendor directory due to

During my attempt to set up mozjpeg within a Docker container running NAME="Alpine Linux" ID=alpine VERSION_ID=3.11.7 PRETTY_NAME="Alpine Linux v3.11" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpin ...