具有反应形式的自定义控件

时间:2019-07-04 11:32:33

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

我正在将Angular 7,Angular Material控件与反应形式一起使用。

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

在我的示例中,这里是stackblitz

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

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

在这方面的任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

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

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

该解决方案正在使用CustomFieldErrorMatcher。如果我们可以创建考虑到customFormControl错误的CustomFiledErrorMatcher,则可以执行以下操作

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,另一种在经典模式下