Need to show the error message in mat errror based on the if condition in component

96 Views Asked by At

I want to show the error message in mat error based on the if condition in component.

export class EditMaterialComponent implements OnInit {

  public quantityRemaining:any;
  public editMaterialForm = new FormGroup({
    count: new FormControl(''),
    suppliedTo: new FormControl('')
  })
  public errormatcher = new MyErrorStateMatcher();
  constructor(private dialogRef: MatDialogRef<EditMaterialComponent>,@Inject(MAT_DIALOG_DATA) public dialogData: any,private inventoryMngService:InventoryMngService) { }

  ngOnInit() {
    console.log(this.dialogData);

  }


  /** CLOSE mat dialog **/
  close() {
    this.dialogRef.close(null);
  }
  updateQuantity(){

    this.dialogData.count = this.dialogData.count - this.editMaterialForm.value.count;
    this.dialogData.comment = this.editMaterialForm.value.suppliedTo;
    if(this.editMaterialForm.valid){
     this.inventoryMngService.updateICase(this.dialogData).subscribe(res=>{
       console.log(res);
       this.close();
      },err=>{
        console.log(err);
      })
    }

}
}

In the updateQuantity(), if this.editMaterialForm.value.count > this.dialogData.count need to show the error in <mat-error></mat-error>. Can anyone help me to solve this?

1

There are 1 best solutions below

5
On BEST ANSWER

You can use a custom validator like this:

export const validateCondition = (condition: (control: AbstractControl) => boolean, errorString: string): ValidatorFn => 
  (control: AbstractControl): ValidatorErrors =>
  (condition(control) ? null : { [errorString]: { value: control.value } });

You can use it like this:

editMaterialForm = new FormGroup({
  count: new FormControl('', [validateCondition(control => control.value > this.dialogData.count, 'myCustomError')]),
  suppliedTo: new FormControl('')
})

Then in your HTML:

<mat-error *ngIf="FormControl.hasError('myCustomError')">message</mat-error>