Search code examples
cssangulartypescripttoasttoastr

How to add custom css to the single Toast message in Angular?


MY QUESTION :

How to add css to the single Toast used in components in Angular, as there can be multiple toast but i want to change a single toast?

Eg toast image : example toast

I want to add my css to the particular toast message.So, that i can align message text in the center i.e File Import started..

how my Angular directory looks like

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

What I Tried :

  1. I added the following codes to my CSS and TS code :

my rough app.css code

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

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 tried \" test \" also

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

      enableHtml : true   //even I have added the messageClass : 'test' 
    });
  }
}

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

  1. by putting my css code into the style.css (main global css) (X I don't want to change my main style)
  2. by adding ::ng-deep .test instead of .test : this is harmful it will change all my toast-dialogue.
  3. by adding encapsulation: ViewEncapsulation.None in @component : but this will change my other Css.
  4. by using <center> tag : still i don't want to do it because it will fix my issue but what if i want to add multiple css.

How can I achieve this?


Solution

  • You need to apply titleClass and messageClass when your toast is used and overwrite the css background-image to align icon and text:

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

    Add css class in your global styles:

    Styles.css:

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

    Or use with :ng-deep if you want to add it in your component's styles css:

    app.component.css

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

    Other alternative is create your own toast component extending Toast and use it customising its template adding a css class for centering the text.

    Using a Custom Toast

    The issue in this case is that you can't override the css background-image property to align icon and text. You can only do that in styles.css

    Changing default icon styles

    Here's the Demo:

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