角度材料 - 具有错误状态的自定义反应式控件

Ran*_*nan 14 angular-material2 angular

我从Angular Material网站关注创建自定义表单控件的本教程.在有验证错误时,教程中没有关于如何遵守表单控制错误的示例.

定制text.component.html

<mat-form-field class="example-full-width">
    <mat-select [placeholder]="placeholder" #select [formControl]="control">
        <mat-option *ngFor="let food of foods" [value]="food">
            {{food}}
        </mat-option>
    </mat-select>
    <mat-error>This is required.</mat-error>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

定制text.component.ts

import { Component, ViewChild, HostBinding, Input, ChangeDetectionStrategy, Optional, Self, DoCheck, OnInit, NgZone } from '@angular/core';
import { ControlValueAccessor, NgControl, NgForm, FormGroupDirective, FormControlDirective, FormControlName, FormControl, FormBuilder } from '@angular/forms';
import { MatFormFieldControl, MatSelect, CanUpdateErrorState, ErrorStateMatcher } from '@angular/material';

@Component({
    selector: 'custom-text',
    templateUrl: './custom-text.component.html',
    styleUrls: [
        './custom-text.component.scss'
    ],
    providers: [
        {
            provide: MatFormFieldControl,
            useExisting: CustomTextComponent
        }
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomTextComponent implements ControlValueAccessor, OnInit, DoCheck {

    @Input()
    foods: string[];

    @Input()
    get errorStateMatcher(): ErrorStateMatcher {
        return this.select.errorStateMatcher;
    }
    set errorStateMatcher(val) {
        this.select.errorStateMatcher = val;
    }

    @Input()
    get placeholder() {
        return this.select.placeholder;
    }
    set placeholder(plh) {
        this.select.placeholder = plh;
        this.stateChanges.next();
    }

    @Input()
    get value() {
        return this.select.value;
    }
    set value(val) {
        this.select.value = val;
        this.stateChanges.next();
    }

    @ViewChild('select')
    select: MatSelect;

    control: FormControl;

    constructor(
        @Optional() @Self() ngControl: NgControl,
        @Optional() private _controlName: FormControlName) {
        if (ngControl) {
            ngControl.valueAccessor = this;
        }
    }

    ngOnInit(): void {
        this.control = this._controlName.control;
    }

    ngDoCheck(): void {
        this.select.updateErrorState();
    }

    writeValue(obj: any): void {
        this.value = obj;
    }
    registerOnChange(fn: any): void {
        this.select.registerOnChange(fn);
    }
    registerOnTouched(fn: any): void {
        this.select.registerOnTouched(fn);
    }
    setDisabledState?(isDisabled: boolean): void {
        this.select.setDisabledState(isDisabled);
    }


}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<div style="text-align:center">
  <form class="example-form" [formGroup]="myForm" (submit)="submitForm()">
    <custom-text [foods]="[null, 'burger', 'spaghetti', 'fries']" 
      formControlName="selectedFood" 
      [errorStateMatcher]="matcher"></custom-text>
    <button>Submit</button>
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)

基本上,我将FormControlName实例注入自定义控件.

constructor(
    @Optional() private _controlName: FormControlName) {
....
ngOnInit(): void {
    this.control = this._controlName.control;
}
Run Code Online (Sandbox Code Playgroud)

然后我将它的control属性绑定到内部mat-select控件中.

<mat-select [placeholder]="placeholder" #select [formControl]="control">
Run Code Online (Sandbox Code Playgroud)

然后我打电话this.select.updateErrorState到里面ngDoCheck.

这是StackBlitz的链接:https://stackblitz.com/edit/angular-c4ufpp

是否有更好或更标准的方法?

Phi*_* J. 7

不要使用创建循环错误依赖项的 Validator 接口,而是添加errorState检查ngControl注入构造函数的自定义组件,如下所示:

get errorState() {
  return this.ngControl.errors !== null && !!this.ngControl.touched;
}
Run Code Online (Sandbox Code Playgroud)

这使得DoCheck不必要。在您的父组件中,不要使用 ,而是errorMatcher使用普通的 Angular 验证器,如下所示:

selectedFood = new FormControl('burger', [Validators.required]);
Run Code Online (Sandbox Code Playgroud)