需要根据组件中的if条件在mat errror中显示错误信息

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

我想根据组件中的if条件在mat错误中显示错误信息。

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

}
}

updateQuantity()中,如果this.editMaterialForm.value.count > this.dialogData.count需要在<mat-error></mat-error>中显示错误。 谁能帮我解决这个问题?

您可以像这样使用自定义验证器:

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

你可以这样使用它:

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

然后在你的 HTML:

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