I'm using PrimeNG and Angular 14. I would like to apply a class (a red border) to my p-dropdown component if the form control contains errors and set another class if it doesn't contain errors. I tried this

      <p-dropdown
      styleClass="border-round-md"
      [ngClass]="{
        'border-red-500':
          submitted && !this.form.get('myName')?.valid
      }"
      [options]="cycleFrPerMonth"
      formControlName="myName"
    ></p-dropdown>

but this doesn't work. Even if there are errors, the error class doesn't display. I have even tried replacing the "submitted && !this.form.get('myName')?.valid" with the word "true" but still nothing doing.

2

There are 2 best solutions below

0
Mouayad_Al On BEST ANSWER

You can try this solution:

  1. When you use ngClass with p-dropdown your class will be apply on the component itself so you have to use styleClass as input in order to apply your class on the first div inside p-dropdown component
  2. Add your class with /deep/ inside scss file of your component like that:
:host ::ng-deep .border-red-500{
 border-color: #007bff !important;
}

3- Instead of using ngClass just use styleClass like this:

   <p-dropdown
      [styleClass]="submitted && !form.get('myName')?.valid 
       ? 'border-red-500' : 'border-round-md' "
      [options]="cycleFrPerMonth"
      formControlName="myName"
    ></p-dropdown>
  1. In your style file:
:host ::ng-deep .border-color {
  // /*your style here */
}

:host ::ng-deep .border-round-md {
   // /*your style here */

}

that should works fine.

3
Souhail Chougrani On

first of all you should verify in angular.json if primeflex.css style is added in

styles:[...,"node_modules/primeflex/primeflex.css"] 

        

if not you should install it : npm install primeflex --save and import it in angular.json styles array

now you should add red color to your primeng palette in style.css file

    :root {
  --red-50: #fff5f5;
  --red-100: #ffd1ce;
  --red-200: #ffada7;
  --red-300: #ff8980;
  --red-400: #ff6459;
  --red-500: #ff4032;
  --red-600: #d9362b;
  --red-700: #b32d23;
  --red-800: #8c231c;
  --red-900: #661a14;
}

last this is an example for your need : stackblitz