0

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

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>。谁能帮我解决这个问题?

4

1 回答 1

0

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

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>
于 2020-01-09T10:42:01.997 回答