How to set up styleClass inside ts file?

444 views Asked by At

I want to create css element inside ts file and pass it as a styleClass to PrimeNg Toast.

var style = document.createElement('style');
style.innerHTML = '::ng-deep .cssClass { background-color: #e62323; border: solid #8A427A; border-width: 0 0 0 6px; color: #2c1e30; }';
this.messageService.add({severity:'custom', summary:'Service Message', detail:'Via MessageService', styleClass: 'cssClass', sticky: true});

The above code is not working for me, style is not applied. Could someone help me with that?

EDIT: I tried to catch the p-toast and append style but it's not applied still.

setTimeout(() => {
  let message = document.getElementsByClassName('p-toast-message-custom')[0];
  message.appendChild(style);
}, 100)
2

There are 2 answers

1
Flo On

In Angular we should not set a style with directly DOM manipulation. The reason is:

  1. Angular cannot detect changes if you do this by hand
  2. Angular render components and create and update the DOM.

So its possible, but not a good way. In your case, set append the element to the DOM. Then it will works, I think.

The Angular Way

Each component has it one contained CSS/SCSS.

What you can do is to use Angulars board means, like ngStyle, ngClass and so on. example:

<div [ngStyle]="{'background-color':'green'}"></<div>

You can do it with property binding, too:

// Code
getColor(country) { (2)
    switch (country) {
      case 'UK':
        return 'green';
      case 'USA':
        return 'blue';
      case 'HK':
        return 'red';
    }
  }

// Html
<div [ngStyle]="{'color':getColor(person.country)}">Test</div>

ngClass does the same but let you set a class flexible to any component.

// Code
val: number = 9;

// Html
<td [ngClass]="val > 10 ? 'red' : 'green'">{{ val }}</td>

Link to ngClass docu, link to ngStyle docu.

2
Zsolt Balint On

To add a class to a message using PrimeNG's MessageService, you can use the add method and provide an optional options object that includes a styleClass property.

Here's an example code snippet that demonstrates how to add a class to a message:

import { Component } from '@angular/core';
import { MessageService } from 'primeng/api';

@Component({
  selector: 'app-my-component',
  template: `
    <button (click)="showSuccess()">Show Success Message</button>
  `,
  providers: [MessageService]
})
export class MyComponent {
  constructor(private messageService: MessageService) {}

  showSuccess() {
    this.messageService.add({severity:'success', summary:'Success', detail:'Message Content', 
      options: {styleClass: 'my-custom-class'}});
  }
}
.my-custom-class {
  background-color: #b3ffb3;
  color: #006600;
  border: 1px solid #006600;
  border-radius: 5px;
  padding: 10px;
}