0

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.

Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

1

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.

Mouayad_Al
  • 1,086
  • 2
  • 13
0

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

  • I would like the drop down outline to have a different CSS class if they try and submit the form but don't select an item from the drop down. Your demo doesn't seem to have that (there's no submit button and I don't see a different CSS class). Am I missing something? – Dave Feb 14 '23 at 13:52
  • you can check this demo https://stackblitz.com/edit/primeng-dropdown-demo-iatxz3?file=src/app/app.component.ts – Souhail Chougrani Feb 14 '23 at 15:13
  • FYI in the first demo I used this.myform.dirty state it's easy to manage form errors...the css class "border-red-500" in the first DEV inside p-dropdown – Souhail Chougrani Feb 14 '23 at 15:22