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

Ways to transfer application routing to "AngularJS" rather than "ASP.NET MVC"

My current project utilizes asp.net MVC in conjunction with angular 8 for the front end. I have successfully loaded all necessary angular files (main.*.js, polyfills.*.js, runtime.*.js) and CSS files in the index of the project. When accessing my s ...

Issue with IE7 causing div elements to slide off the screen on specific WordPress pages

Encountering a strange IE7 bug on two pages of a WordPress site I'm currently developing. Some divs are shifting to odd positions, with one completely off the screen: and another here: Additionally, possibly related or not, the "created by" link in ...

Challenge with CSS3 Selectors

I'm struggling to understand why this code works: input[ type = "text" ]:last-of-type:focus{ border:1px solid red; } but this code doesn't work: input[ type = "checkbox" ]:last-of-type:checked{ border:1px solid red; } The example given with t ...

Incorporating fresh data from a node.js backend to refresh a webpage section

I'm currently working on creating an app that can retrieve the song a user is currently listening to using a web scraper. While I've managed to direct users to the page and display the current song title, they must manually refresh the entire pag ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

Having difficulties creating a new instance of a class

I'm encountering an issue with this TypeScript code import Conf = require('conf'); const config = new Conf(); The Problem: the expression is not constructable and the imported module lacks construct signatures It's puzzling because th ...

I am struggling to grasp the concept of ref unwrapping within a TypeScript template

I'm currently in the process of converting some Vue3 code from javascript to typescript, and I am struggling to comprehend the unwrapping of a ref/computed value in the template. I used to believe that the template would automatically unwrap reactiv ...

Tips for expanding the content of a blogger page to fill the entire frame of the page

Check out this page: . Currently, the video on the page does not fill up the entire screen. Any suggestions for a solution? ...

The Npm audit inspection revealed a single low-risk vulnerability within the karma > expand-braces > braces component

The Npm audit report has flagged 'found 1 low severity vulnerability'. Manual review is needed for this vulnerability. Low Regular Expression Denial of Service Package braces Patched in >=2.3.1 Dependency of ...

"Stylish hover effect for list items using CSS arrows

I'm struggling with creating a list menu that has a 1px border and spans the entire width. Here is what I have so far (image 1): https://i.stack.imgur.com/y3EDP.png The tricky part is making it so that when the mouse hovers over a menu item, someth ...

Mastering Theme Transformation with SASS

My website is constructed using SASS, and I am facing an issue where the variables I set for light and dark themes are not changing as expected. Whenever I switch between themes, all variables revert to their original values, making it difficult for me to ...

How can you dynamically disable the submit button on a form in Angular 7+ based on the form's current status?

Let's consider a scenario with a button in our code: <button type="button" class="menu-button" [disabled]="isInvalidForm()">Save</button isInvalidForm() { console.log('I am running!'); return this.nameValidator.errors || this.last ...

Why does the div inside the tbody element get automatically shifted outside of the tbody during rendering?

Below is a snippet of my code: <body> <table> <tbody> <div>test</div> </tbody> </table> </body> Upon executing the code mentioned above, it transformed automatically in ...

Jhipster - displaying the authenticated user on an Angular Frontend

Is there a way to retrieve the ID of the currently logged in user from the frontend of an Angular application generated by Jhipster? I have come across some older solutions using the Principal class, but it appears that method is no longer available. Any ...

Import Information into Popup Window

When a user clicks on the "view" button, only the details of the corresponding challenge should be displayed: Currently, clicking on the "view" button loads all the challenges. This is because in my view-one-challenge.component.html, I have coded it as fo ...

Adjust the size of the input form

Trying to create this design: But currently stuck with this layout: I'm puzzled on how to resize the input field with an icon on the right while using col-md-12... Check out my code below: .form { margin-top: 8px; margin-left: 13px; displ ...

Improved efficiency in CSS for left transition animations

Here is the current code I am using: .s2 { top: 150px; left: 20px; position: absolute; transition: left 300ms linear; } I am currently updating the left position dynamically using JavaScript based on scroll events. However, I have noticed that th ...

Is it possible to adjust the left property following the concealment of an element with JQuery?

My goal is to move an image element using the 'left' property after hiding a div. To achieve this, I am using JQuery's '.promise()' function. Here is my code: HTML code: <div id="outerContainer"> <div id=" ...

The intersection of CSS and IE7's Z-Index feature

Hey there, I could really use some help! If anyone has any ideas for fixing a z-index issue in Internet Explorer 7 with CSS/JavaScript on this page while keeping the DOM structure intact (it's currently optimized for easy tab navigation), I would gre ...

Having trouble correctly displaying a form with nested form array within a form group

I am working with a form group that contains nested form groups and a form array: ngOnInit() { this.form = this.fb.group({ dropDownOptions: this.fb.group({ items: this.fb.array([this.createItem()]) }) ...