Angular FormControl 未检测到输入指令所做的更改

所以我有一个指令(我不能相信)它只允许用户输入整个非负数。它工作正常,但问题是与 formcontrol 字段相关的 matInput 没有接受更改。预先感谢您提供有关解决此问题的任何建议。

这是指令:

import { Directive,ElementRef,HostListener,Input } from "@angular/core";

@Directive({
  selector: "[numeric]"
})
export class NumericDirective {
  @Input("decimals") decimals: number = 0;
  @Input("negative") negative: number = 0;
  @Input("separator") separator: string = ".";

  private checkAllowNegative(value: string) {
    if (this.decimals <= 0) {
      return String(value).match(new RegExp(/^-?\d+$/));
    } else {
      var regExpString =
        "^-?\\s*((\\d+(\\"+ this.separator +"\\d{0," +
        this.decimals +
        "})?)|((\\d*(\\"+ this.separator +"\\d{1," +
        this.decimals +
        "}))))\\s*$";
      return String(value).match(new RegExp(regExpString));
    }
  }

  private check(value: string) {
    if (this.decimals <= 0) {
      return String(value).match(new RegExp(/^\d+$/));
    } else {
      var regExpString =
        "^\\s*((\\d+(\\"+ this.separator +"\\d{0," +
        this.decimals +
        "}))))\\s*$";
      return String(value).match(new RegExp(regExpString));
    }
  }

  private run(oldValue: any) {
    setTimeout(() => {
      let currentvalue: string = this.el.nativeElement.value;
      let allowNegative = this.negative > 0 ? true : false;

      console.log(this.el.nativeElement.value)
      
      console.log(oldValue)
      if (allowNegative) {
        if (
          !["","-"].includes(currentvalue) &&
          !this.checkAllowNegative(currentvalue)
        ) {
          this.el.nativeElement.value = oldValue;
        }
      } else {
        if (currentvalue !== "" && !this.check(currentvalue)) {
          this.el.nativeElement.value = oldValue;
        }
      }
    });
  }

  constructor(private el: ElementRef) {}

  @HostListener("keydown",["$event"])
  onKeyDown(event: KeyboardEvent) {
    this.run(this.el.nativeElement.value);
  }

  @HostListener("paste",["$event"])
  onPaste(event: ClipboardEvent) {
    this.run(this.el.nativeElement.value);
  }
}

这是输入的html:

<mat-form-field appearance="fill" class="field">
                <mat-label>Select Number Of Item(s) to {{data.action | titlecase}}</mat-label>
                <input matInput numeric type="number" formControlName="quantity"
                    [placeholder]="'Available Quantity ' + data.item.quantity">
                <div
                    *ngIf="this.actionFormGroup.get('quantity').invalid && (this.actionFormGroup.get('quantity').dirty || this.actionFormGroup.get('quantity').touched)">
                    <div *ngIf="this.actionFormGroup.get('quantity').errors.max">
                        <mat-error>
                            Exceeded Item Quantity
                        </mat-error>
                    </div>
                    <div *ngIf="this.actionFormGroup.get('quantity').errors.min">
                        <mat-error>
                            Minimum Quantity of 1 Required
                        </mat-error>
                    </div>
                </div>
            </mat-form-field>

这里是表单控件声明:

  setformGroup(): void {
this.actionFormGroup = new FormGroup({
  quantity: new FormControl('',[Validators.required,Validators.min(1),Validators.max(this.data.item.quantity),Validators.pattern('^(0|[1-9][0-9]*)$')]),destination: new FormControl(this.getDestination(),Validators.required)
});
if (this.data.item.quantity === 1) {
  this.actionFormGroup.get("quantity")!.setvalue(1);
}

}

cctvmtv1982 回答:Angular FormControl 未检测到输入指令所做的更改

您可以像这样使用 NgControl 将此 FormControl 注入您的 directive

constructor(private el: ElementRef,@Optional() @Host() private ngControl: NgControl) {
  }

并用它来更新输入的值

...
if (!['','-'].includes(currentValue) &&
    !this.checkAllowNegative(currentValue)) {
    if (this.ngControl) {
      this.ngControl.control.setValue(oldValue);
    } else {
      this.el.nativeElement.value = oldValue;
    }
}
...

还有这里(在您的指令中的任何其他类似地方都这样做)

@HostListener('keydown',['$event'])
  onKeyDown(event: KeyboardEvent) {
    if (this.ngControl) {
      this.run(this.ngControl.control.value);
    } else {
      this.run(this.el.nativeElement.value);
    }
  }
本文链接:https://www.f2er.com/8666.html

大家都在问