Search code examples
cssprimengform-controlangular14p-dropdown

With PrimeNG and Angular 14, how do I change my CSS class based on whether there is an error on my p-dropdown component?


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.


Solution

  • 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.