Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

angular reusaable component add class error

I am making a mat select reusable component but I can’t add a Scss class if there is an error and when there is no more error the class is removed.

I try to add a class if the input is in error but the input remains red even when there is no more error [Edit: from code comment]

html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<mat-form-field appearance="legacy" [class.inputColorError]="controler.markAsDirty()"> <!-- here I try to add a class if the input is in error but the input remains red even when there is no more error  -->

  <!-- left-side-icon -->
  <mat-icon matPrefix *ngIf="leftSideIcon" class="leftIconStyle" [class.left-icon-error-border]="controler.touched"
    [matTooltip]="matTooltip" [matTooltipDisabled]="controler.invalid">
    {{leftSideIcon}}
  </mat-icon>

  <!-- mat-select -->
  <mat-select [formControl]="controler" disableOptionCentering="true" panelClass="panelClass"
    (selectionChange)="onSelectionChange($event)" [disabled]="disabled" [required]="required" [matTooltip]="matTooltip"
    [matTooltipDisabled]="!controler.touched">

    <!-- mat-options -->
    <mat-option *ngFor="let item of options | keyvalue" value="{{item.key}}">
      {{item.value}}
    </mat-option>

  </mat-select>
</mat-form-field>

scss

.inputColorError {
  color: red;

  ::ng-deep {
    .mat-form-field-flex {
      border-bottom: black;
    }

    .mat-form-field-label {
      color: black;
    }

    .mat-form-field.mat-focused .mat-form-field-ripple,
    .mat-form-field-ripple {
      background: none;
    }
  }
}

>Solution :

here I try to add a class if the input is in error but the input remains red even when there is no more error

There’s no need to overwrite the internal styles.

Use the error state matcher to decide when field should show errors.

https://material.angular.io/components/input/overview#changing-when-error-messages-are-shown

If the input is red however it’s likely your validators are saying the control is invalid and adding the ng-invalid class to the form field i.e. your validators are the source of the problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading