我正在制作一个自定义日期选择器组件,以便它可以与本地化和 moment.js 以及反应形式一起使用。
我已经设置了组件,但是在 DateChange 事件之后,在它退出区域后,它会抛出一个错误:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-valid: true'. Current value: 'ng-valid: false'.
目前,我不知道如何修复它,尽管我试图修复它,ChangeDetectorRef
这使得我的验证无法触发,类似的事情也会发生在this.control.updateValueAndValidty()
.
毕竟,它发生得比我触发任何事情都要晚很多。我想这是输入元素的问题,所以我会尝试同时捕捉它的变化事件。
所以这是date-picker.component.ts
:
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { Component, OnInit, forwardRef, Input, Self, Optional, ChangeDetectorRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, Validator, NG_VALIDATORS, FormControl, NgControl, FormControlName } from '@angular/forms';
import * as _moment from 'moment';
import { MatDatepickerInputEvent, MAT_DATE_FORMATS, DateAdapter, MAT_DATE_LOCALE } from '@angular/material';
import { default as _rollupMoment } from 'moment';
const moment = _rollupMoment || _moment;
export const DATE_FORMATS = {
parse: {
dateInput: 'DD.MM.YYYY.',
},
display: {
dateInput: 'DD.MM.YYYY.',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-date-picker',
templateUrl: './date-picker.component.html',
styleUrls: ['./date-picker.component.scss'],
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'sr' },
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS }
]
})
export class DatePickerComponent implements ControlValueAccessor {
control: FormControl;
private onChange = (value: any) => { };
private onTouched = (value: any) => { };
@Input() dateValue: string = null;
@Input() errorMessage: string = "This is required.";
@Input() public placeholder: string = null;
@Input() public minDate: string = null;
@Input() public maxDate: string = null;
@Input() public startDate: string = null;
@Input() public label: string = null;
constructor(@Optional() @Self() private ngControl: NgControl, @Optional() private controlName: FormControlName, private cdr: ChangeDetectorRef) {
if(this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
ngOnInit() {
moment.locale('sr');
this.control = this.controlName.control;
}
onDateChange(event: MatDatepickerInputEvent<Date>) {
this.dateValue = moment(event.value).format();
this.onChange(event.value);
}
// get errorState() {
// debugger;
// if(!this.dateValue){
// return this.ngControl.errors !== null && !!this.ngControl.touched;
// }
// return false;
// }
// ControlValueAccessor methods
writeValue(value: any): void {
if(value !== undefined || value !== '') {
this.dateValue = moment(value).format();
}
}
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched() {}
// registerOnTouched(fn) {
// this.onTouched = fn;
// }
}
这是date-picker.component.html
:
<div class="date-picker">
<mat-form-field class="full-width">
<mat-label>{{ label }}</mat-label>
<input #dpInput matInput
[matDatepicker]="componentDatePicker"
(dateChange)="onDateChange($event)"
[formControl]="control"
[value]="dateValue"
[min]="minDate"
[max]="maxDate"
[placeholder]="placeholder"
[formControl]='control'>
<mat-datepicker-toggle matSuffix [for]="componentDatePicker"></mat-datepicker-toggle>
<mat-datepicker #componentDatePicker></mat-datepicker>
<mat-error [innerHTML]="errorMessage"></mat-error>
</mat-form-field>
</div>
我正在通过返回带有值或的对象来更改父组件中的min
和值。同一个选择器有多个实例,所以我发送字符串值来区分它们。max
new Date(year, month, day)
null
<app-date-picker
[minDate]="getMinDate('datepickerIdentifier')"
[maxDate]="getMaxDate('datepickerIdentifier')"
[placeholder]="'Placeholder string'"
[label]="'Label string'"
[errorMessage]="'Error string'"
formControlName="applicationEnd"
required>
</app-date-picker>
我试图构建可重用的 datepicker 组件,该组件将具有本地化、特定的日期格式,并且可以轻松地合并到反应式表单中,因此我可以使用其余的表单数据对其进行验证,并显示Validation.required
错误。
不幸的是,我不知道从哪里开始调试它。
编辑:我试图制作一个stackblitz,但它给了我很多错误,但仍然是: https ://stackblitz.com/edit/angular-aylptw