为了展示一个真实世界的例子,假设我们想在我们的应用程序中使用@angular/material 的日期选择器。
我们想在很多页面上使用它,所以我们想让它很容易地添加到任何地方都具有相同配置的表单中。为了满足这个需求,我们在一个带有 ControlValueAccessor 实现的周围创建了一个自定义的角度组件<mat-datepicker>
,以便能够[(ngModel)]
在它上面使用。
我们希望处理组件中的典型验证,但同时,我们希望使验证结果可用于包含我们的CustomDatepickerComponent
.
作为一个简单的解决方案,我们可以实现这样的validate()
方法(innerNgModel 来自导出的 ngModel: #innerNgModel="ngModel"
。请参阅本问题末尾的完整代码):
validate() {
return (this.innerNgModel && this.innerNgModel.errors) || null;
}
此时,我们可以以非常简单的方式(如我们所愿)在任何表单组件中使用日期选择器:
<custom-datepicker [(ngModel)]="myDate"></custom-datepicker>
我们还可以扩展上面的行以获得更好的调试体验(像这样):
<custom-datepicker [(ngModel)]="myDate" #date="ngModel"></custom-datepicker>
<pre>{{ date.errrors | json }}</pre>
只要我更改自定义日期选择器组件中的值,一切正常。如果日期选择器有任何错误,则周围的表单仍然无效(如果日期选择器有效,则它变为有效)。
但!
如果myDate
外部表单组件的成员(作为 ngModel 传递)被外部组件更改(如:)this.myDate= null
,则发生以下情况:
writeValue()
CustomDatepickerComponent 运行,它更新日期选择器的值。- CustomDatepickerComponent的
validate()
运行,但此时innerNgModel
没有更新,因此它返回早期状态的验证。
为了解决这个问题,我们可以在 setTimeout 中从组件发出更改:
public writeValue(data) {
this.modelValue = data ? moment(data) : null;
setTimeout(() => { this.emitChange(); }, 0);
}
在这种情况下,emitChange(自定义组件的广播更改)将触发新的验证。并且由于 setTimeout,当 innerNgModel 已经更新时,它将在下一个周期运行。
我的问题是,是否有比使用 setTimeout 更好的方法来处理这个问题? 如果可能的话,我会坚持模板驱动的实现。
提前致谢!
示例的完整源代码:
自定义 datepicker.component.ts
import {Component, forwardRef, Input, ViewChild} from '@angular/core';
import {ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgModel} from '@angular/forms';
import * as moment from 'moment';
import {MatDatepicker, MatDatepickerInput, MatFormField} from '@angular/material';
import {Moment} from 'moment';
const AC_VA: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomDatepickerComponent),
multi: true
};
const VALIDATORS: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CustomDatepickerComponent),
multi: true,
};
const noop = (_: any) => {};
@Component({
selector: 'custom-datepicker',
templateUrl: './custom-datepicker.compnent.html',
providers: [AC_VA, VALIDATORS]
})
export class CustomDatepickerComponent implements ControlValueAccessor {
constructor() {}
@Input() required: boolean = false;
@Input() disabled: boolean = false;
@Input() min: Date = null;
@Input() max: Date = null;
@Input() label: string = null;
@Input() placeholder: string = 'Pick a date';
@ViewChild('innerNgModel') innerNgModel: NgModel;
private propagateChange = noop;
public modelChange(event) {
this.emitChange();
}
public writeValue(data) {
this.modelValue = data ? moment(data) : null;
setTimeout(() => { this.emitChange(); }, 0);
}
public emitChange() {
this.propagateChange(!this.modelValue ? null : this.modelValue.toDate());
}
public registerOnChange(fn: any) { this.propagateChange = fn; }
public registerOnTouched() {}
validate() {
return (this.innerNgModel && this.innerNgModel.errors) || null;
}
}
和模板(custom-datepicker.compnent.html):
<mat-form-field>
<mat-label *ngIf="label">{{ label }}</mat-label>
<input matInput
#innerNgModel="ngModel"
[matDatepicker]="#picker"
[(ngModel)]="modelValue"
(ngModelChange)="modelChange($event)"
[disabled]="disabled"
[required]="required"
[placeholder]="placeholder"
[min]="min"
[max]="max">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="innerNgModel?.errors?.required">This field is required!</mat-error>
<mat-error *ngIf="innerNgModel?.errors?.matDatepickerMin">Date is too early!</mat-error>
<mat-error *ngIf="innerNgModel?.errors?.matDatepickerMax">Date is too late!</mat-error>
</mat-form-field>
周边微模块(custom-datepicker.module.ts):
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MatDatepickerModule, MatFormFieldModule, MatInputModule, MAT_DATE_LOCALE, MAT_DATE_FORMATS} from '@angular/material';
import {CustomDatepickerComponent} from './custom-datepicker.component';
import {MAT_MOMENT_DATE_ADAPTER_OPTIONS, MatMomentDateModule} from '@angular/material-moment-adapter';
import {CommonModule} from '@angular/common';
const DATE_FORMATS = {
parse: {dateInput: 'YYYY MM DD'},
display: {dateInput: 'YYYY.MM.DD', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY'}
};
@NgModule({
imports: [
CommonModule,
FormsModule,
MatMomentDateModule,
MatFormFieldModule,
MatInputModule,
MatDatepickerModule
],
declarations: [
CustomDatepickerComponent
],
exports: [
CustomDatepickerComponent
],
providers: [
{provide: MAT_DATE_LOCALE, useValue: 'es-ES'},
{provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS},
{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: false}}
]
})
export class CustomDatepickerModule {}
以及部分外部表单组件:
<form #outerForm="ngForm" (ngSubmit)="submitForm(outerForm)">
...
<custom-datepicker [(ngModel)]="myDate" #date="ngModel"></custom-datepicker>
<pre>{{ date.errors | json }}</pre>
<button (click)="myDate = null">set2null</button>
...