我为日期选择器编写了如下的控件值访问器,
import { Component, Input, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import * as _moment from 'moment';
import {default as _rollupMoment} from 'moment';
const moment = _rollupMoment || _moment;
@Component({
selector: 'app-date-picker',
template: `
<mat-form-field placeholder="date" appearance="outline">
<mat-label>{{title}}</mat-label>
<mat-datepicker-toggle matPrefix [for]="picker"></mat-datepicker-toggle>
<input matInput [matDatepicker]="picker" [value]="dateValue" (dateInput)="addEvent('input', $event)" [placeholder]="title">
<mat-datepicker touchUi="true" #picker></mat-datepicker>
</mat-form-field>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatePickerComponent),
multi: true
}
],
styleUrls: ['./date-picker.component.scss']
})
export class DatePickerComponent implements ControlValueAccessor {
constructor() { }
@Input()
_dateValue; // notice the '_'
@Input() title: string;
get dateValue() {
return moment(this._dateValue, 'YYYY-MM-DD HH:mm:ss');
}
set dateValue(val) {
this._dateValue = moment(val).format('YYYY-MM-DD HH:mm:ss');
this.propagateChange(this._dateValue);
}
addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
// console.log(event.value);
this.dateValue = moment(event.value, 'YYYY-MM-DD HH:mm:ss');
}
writeValue(value: any) {
if (value !== undefined) {
this.dateValue = moment(value, 'YYYY-MM-DD HH:mm:ss');
}
}
propagateChange = (_: any) => { };
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched() { }
}
我正在html组件中使用上述日期选择器,如下所示,
<app-date-picker [ngModel]="toDate" class="form" [title]="'To'" formControlName="toDate"></app-date-picker>
在component.ts文件中,我有一个包含formControlName的表单,
this.myDate = new Date();
this.toDate = this.datepipe.transform(this.myDate, 'dd/MM/yyyy');
console.log(this.toDate);
this.issueSearchForm = this.formBuilder.group(
{
userId: [''],
isMobileNo: [''],
fromDate: [''],
toDate: [this.toDate, Validators.required],
issueType: [this.defaultIssueType, Validators.required]
}
);
console.log输出显示值为
01/10/2018
但是在选择器组件中,将其设置为
2001/10/20
我要去哪里了,请帮助我。