Home > Mobile >  angular reusaable component add class error
angular reusaable component add class error

Time:11-04

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

<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.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;
    }
  }
}

CodePudding user response:

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.

  • Related