【问题标题】:Custom Controls with Reactive Forms具有响应式表单的自定义控件
【发布时间】:2019-11-15 03:24:46
【问题描述】:

我正在使用 Angular 7,带有反应形式的 Angular Material 控件。

我使用带有 mat-form-field 的 Angular Material 创建了自定义文本 (matInput type="text")、数字 (matInput type="number")、选择 (matSelect) 控件

这是我的示例stackblitz

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

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

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

【问题讨论】:

标签: angular angular-material angular7 angular-reactive-forms reactive-forms


【解决方案1】:

更新 Jenson-button-event 找到更好的选择,请参阅SO answer

查看您的代码,我发现您使用 Angular Material 创建自定义 FormControl。那么,使用 Angular 材质时的问题是如何使“错误”出现。

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

解决方案是使用 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,另一种使用 clasic 模式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多