Tips for applying personalized CSS to individual Toast notifications in Angular

MY QUESTION :

I am looking to customize the CSS of a single toast used in Angular components. While there may be multiple toasts, I specifically want to style one particular toast differently.

For example, the toast image can be viewed here: example toast

The goal is to add custom CSS to this specific toast message so that I can center align the text, such as "File Import started.."

This is how my Angular directory is structured:

| app
    |
    |-components
    |    |
    |    |-test [/app.ts , /app.css]
    |
    |style.css
    

What I Tried :

  1. I attempted to modify both the CSS and TS code as follows:

My rough app.css code:

.test {
   text-align : center !important // I also tried without ! important
}

My rough app.ts code

import { Component } from '@angular/core';
import {ToastrService} from 'ngx-toastr';

@Component({
  selector: 'my-app',
  templateUrl: './app.html',
  styleUrls: [ './app.css' ]
})

export class app {
  constructor(private toastr: ToastrService) {}

  showSuccess() { 

       // I also tried using \"test\"

    this.toastr.success('<span class="test">File import started</span>', '', {

      enableHtml : true   //even with messageClass : 'test' added 
    });
  }
}

HOW IT WORKED BUT I DON'T WANT THESE APPROACHES:

  1. Adding the CSS code into the global style.css (X I prefer not to change main styles).
  2. Using ::ng-deep .test instead of .test: although effective, it affects all toast dialogues.
  3. Applying
    encapsulation: ViewEncapsulation.None
    in @component: alters other CSS styles.
  4. Using <center> tag: while a quick solution, limits adding additional CSS rules.

How can I achieve this customization for a single toast?

Answer №1

To properly display your toast message, you must include the titleClass and messageClass classes in your code and adjust the css background-image to ensure proper alignment of the icon and text:

 showSuccess() {
    this.toastr.success("Hello world!", "Toastr fun!", {
      titleClass: "center",
      messageClass: "center"
    });
  }

Add the following css classes to your global styles:

Styles.css:

.center {
  text-align: center;
}

.toast-success {
  padding-left: 80px;
  text-align: center;
  background-position: 35% !important;
}

Alternatively, use :ng-deep in your component's styles if needed:

app.component.css

:ng-deep .center {
  text-align: center;
}

If necessary, create a custom toast component by extending Toast and customize its template with a css class for centering the text.

Using a Custom Toast

Note that it may be challenging to override the css background-image property for aligning the icon and text, as it can only be modified in styles.css.

Changing default icon styles

Check out the Demo here:

https://stackblitz.com/edit/ngx-toastr-angular2-4pqrqw

Answer №2

To customize the appearance of the toast message, you can utilize the titleClass property in your application.

import {ToastrService} from 'ngx-toastr';

@Component({
  selector: 'my-app',
  templateUrl: './app.html',
  styleUrls: [ './app.css' ]
})

export class MyComponent {
  constructor(private toastr: ToastrService) {}

  showSuccess() { 
    this.toastr.success('Data saved successfully', '', {
      titleClass: 'custom-title-class' // This will apply the custom-title-class to the toast title.
    });
  }
}

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 sets apart a search bar from a text field?

What distinguishes a searchbar from a textfield? Is there a way to eliminate the search icon in a searchbar? ...

Show a component on click event in Angular 4

Looking for a solution to create an event on a button click that triggers another component? When clicked again, the component should be reduced with a part always remaining visible. While I am currently using [ngClass]='hidden' within the same c ...

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

Interactive sidebar scrolling feature linked with the main content area

I am working with a layout that uses flexboxes for structure. Both the fixed sidebar and main container have scroll functionality. However, I have encountered an issue where scrolling in the sidebar causes the scroll in the main container to activate whe ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

Issue: Trouble with Rotating Tooltips in Javascript

I am facing a challenge with the tooltips on my website. I want to ensure that all tooltips have a consistent look and transition effects, but I am struggling to achieve this. The rotation and other effects applied using javascript are not functioning prop ...

Troubleshooting Challenges with Installing Angular 5, Node.js, and N

I currently have Node and NPM installed with the most recent versions. When attempting to install Angular/cli, I encountered an error message stating: angular/cli and npm versions not compatible with current version of node. I am beginning to think that I ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

How can TypeScript be used to update the values and text of an HTML element?

Is it possible to update specific attributes of an html element using typescript? Below is the code snippet: HTML:- <a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left ...

How to update a variable in the app.config.json file in Angular 5

I've created a custom asset JSON configuration file called .angular-cli.json to use as default. However, there are certain instances where I need to update specific values within this file but I'm not sure how to go about it. Any suggestions? .a ...

Displaying updated information in Angular

I recently developed a chat application using Angular that utilizes the stomp socket from @stomp/ng2-stompjs. To display all messages, I am leveraging *ngFor. <p *ngFor="let item of messages" style="padding: 5px; font-size: 18px"> <span style ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

Creating a torn paper illusion using CSS masking techniques

My goal is to create a ripped/lined paper effect using CSS mask. It's working well and looks good. However, I'm struggling to apply the mask at the top as well. Here's what I've tried so far: mask-image: linear-gradient(white, white), u ...

What's the best way to enable touch scrolling for items within a div container?

I am in the process of creating a code snippet that will allow users to scroll through items within a div, similar to a spinning wheel or slot machine. While I am aware of an existing solution for iPhone and iPod, I want to develop a simpler, more streamli ...

Encountering an issue when trying to upload numerous base64 images to Cloudinary through Node.js and receiving an error with code -4064, specifically 'ENAMETOOLONG'

I'm encountering an issue with base64 URLs when trying to upload multiple images to Cloudinary. When I send only one image, it gets uploaded correctly, but when sending multiple images, I receive an error 'ENAMETOOLONG' with error number 406 ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

End the pipeline execution in a chain of RxJS observables

Here is a scenario where a series of Observables are chained together. Is it possible to prevent the subsequent chain from executing if an error is thrown by 'parentObs1'? import { throwError } from "rxjs"; import { mergeMap, catchError ...

Having trouble with displaying the CSS background image?

I've been attempting to configure background images using CSS, but for some reason, I'm not able to get the images to show up correctly. Below is the CSS code that I'm working with: a.fb { background-image: url('img/Facebook.png&a ...

Configuring VS Code's "tasks.json" file to compile all .ts files can be done by following these steps

Apologies if this question has been asked before, but could someone please redirect me to the relevant thread if so. I am wondering if it is possible to set up VS Code's "tasks.json" to automatically compile all .ts files within a folder. Currently, I ...