You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular组件中如何通过if条件控制mat-error显示库存不足错误?

How to Show mat-error When Entered Quantity Exceeds Remaining Stock

Got it, let's walk through this step by step to get your mat-error working exactly how you need it. The goal is to display an error message when the user enters a count greater than the remaining quantity (dialogData.count), both when they submit the form and ideally as they type.

Step 1: Update the Component Logic

First, we'll modify your updateQuantity() method to check the count condition, set a custom form error if needed, and block the update until the input is valid. We'll also add optional real-time validation so the error shows as the user types.

Modify the updateQuantity() Method

updateQuantity(){
  // Convert form value to number (since FormControl returns string by default)
  const inputCount = Number(this.editMaterialForm.get('count')?.value);
  const remainingCount = this.dialogData.count;

  // Clear any existing custom error first
  const countControl = this.editMaterialForm.get('count');
  if (countControl?.hasError('exceedsRemaining')) {
    delete countControl.errors?.exceedsRemaining;
    if (Object.keys(countControl.errors || {}).length === 0) {
      countControl.setErrors(null);
    }
  }

  // Check if input exceeds remaining quantity
  if (inputCount > remainingCount) {
    countControl?.setErrors({ exceedsRemaining: true });
    return; // Stop execution so we don't proceed with the update
  }

  // Proceed with your original update logic if validation passes
  this.dialogData.count = remainingCount - inputCount;
  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);
    })
  }
}

Optional: Add Real-Time Validation

To show the error as the user types instead of only when they click the update button, add this to your ngOnInit() method:

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

  // Listen for changes to the count input and validate in real-time
  this.editMaterialForm.get('count')?.valueChanges.subscribe(value => {
    const inputCount = Number(value);
    const remainingCount = this.dialogData.count;
    const countControl = this.editMaterialForm.get('count');

    if (inputCount > remainingCount) {
      countControl?.setErrors({ exceedsRemaining: true });
    } else {
      // Clear the custom error but keep other validation errors (like required)
      if (countControl?.hasError('exceedsRemaining')) {
        delete countControl.errors?.exceedsRemaining;
        if (Object.keys(countControl.errors || {}).length === 0) {
          countControl.setErrors(null);
        }
      }
    }
  });
}

Step 2: Update the Template

Now, modify your template to display the mat-error when the custom exceedsRemaining error exists. Make sure your mat-form-field is set up correctly with the error state matcher:

<mat-form-field appearance="fill">
  <input 
    matInput 
    formControlName="count" 
    type="number" 
    placeholder="Enter Quantity"
    [errorStateMatcher]="errormatcher"
  >
  <!-- Custom error for exceeding remaining quantity -->
  <mat-error *ngIf="editMaterialForm.get('count')?.hasError('exceedsRemaining')">
    Quantity cannot exceed remaining stock ({{ dialogData.count }})
  </mat-error>
  <!-- Optional: Add other validation errors like required -->
  <mat-error *ngIf="editMaterialForm.get('count')?.hasError('required')">
    Quantity is required
  </mat-error>
</mat-form-field>

<!-- Your update button -->
<button mat-raised-button color="primary" (click)="updateQuantity()">Update Quantity</button>

Step 3: Verify Your Error State Matcher

Ensure your MyErrorStateMatcher correctly detects when to show errors. If you haven't already, make sure it checks if the control is touched or the form is submitted:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    // Show error if control is invalid AND (touched OR form submitted)
    return !!(control && control.invalid && (control.touched || isSubmitted));
  }
}

This setup will:

  • Block the update when the input count exceeds remaining stock
  • Show the error message in mat-error when the condition is met
  • Optionally show the error as the user types for better UX

内容的提问来源于stack exchange,提问作者ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:23:12