带有响应式表单的自定义控件

Custom Controls with Reactive Forms

我正在使用 Angular 7,Angular Material 控件和 Reactive Forms。

我创建了自定义文本 (matInput type="text")、数字 (matInput type="number")、select (matSelect) 控件 Angular Material 与 mat-form-field

这是我的示例 stackblitz

我正在尝试将自定义表单控件附加到反应式表单并尝试自动触发表单组上的任何验证。

我正在使用 ControlValueAccessor 来实现这一点,但是我的 Select 没有被识别为表单控件,并且没有值被记录在表单的表单控件中。

非常感谢这方面的任何帮助。

更新 Jenson-button-event 找到更好的选择,见

查看您的代码,我发现您使用 Angular Material 创建自定义 FormControl。那么,使用 Angular material 时的问题是如何使 "errors" 出现。

当我们使用 <mat-error> 时,如果控件无效,则会出现错误。考虑到我们的自定义表单控件无效,而不是 input-material。如何避免这种不便?

解决方案是使用 CustomFieldErrorMatcher。如果我们可以创建一个 CustomFiledErrorMatcher 来考虑我们的 customFormControl 的错误,我们可以做一些像

class CustomFieldErrorMatcher implements ErrorStateMatcher {
  constructor(private customControl: FormControl) { }
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return control.dirty && this.customControl.invalid;
  }
}

嗯,只能在ngAfterView里写点像

  ngAfterViewInit(): void {
    const ngControl: NgControl = this.injector.get(NgControl, null);
    if (ngControl) {
      setTimeout(() => {
        this.control = ngControl.control as FormControl;
      })
    }
  }

有功能

errorMatcher() {
    return new CustomFieldErrorMatcher(this.control)
  }

并创建我们的 custom-formControl.html 喜欢

<mat-form-field>
    <mat-select [ngModel]="value" (ngModelChange)="value=$event;onChange($event)" 
          [placeholder]="placeholder" [disabled]="disabled"
          [errorStateMatcher]="errorMatcher()">
        <mat-option *ngFor="let option of optionList" [value]="option.value">
            {{ option.label }}
        </mat-option>
    </mat-select>
  <mat-error *ngIf="control?.hasError('required')">Required</mat-error>
  <mat-error *ngIf="control?.hasError('error')">{{control?.errors.error}}</mat-error>
</mat-form-field>

您可以在 stackblitz 中看到两种形式,一种使用 customFormControl,另一种采用经典模式