-
Notifications
You must be signed in to change notification settings - Fork 6
Description
Hi,
I am trying to apply your code inside my reactive form so that I can save a custom date format. When I use the field and look at the value it generates it works fine, but when I open the form of an existing object, the field is not filled with the form control value. If I select a new date, the field is filled and I can see the form control is filled with the new value. What's going wrong?
My parent html code:
<app-date-picker placeholder="{{ 'Captions.RealEstateGuarantee.ExpertiseDate' | translate}}" formControlName="ExpertiseDate" format="YYYY/MM/DDTHH:mm:ss"> </app-date-picker>
date-picker.component.html
<mat-form-field> <mat-datepicker-toggle matPrefix [for]="picker"></mat-datepicker-toggle> <input matInput formControlName="formName" [matDatepicker]="picker" value="dateValue" (dateInput)="addEvent('input', $event)" [placeholder]="placeholder"> <mat-datepicker #picker></mat-datepicker> </mat-form-field>
date-picker.component.ts:
`import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import * as moment from 'moment';
@component({
selector: 'app-date-picker',
templateUrl: './date-picker.component.html',
styleUrls: ['./date-picker.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatePickerComponent),
multi: true
}
]
})
export class DatePickerComponent implements ControlValueAccessor {
@input() _dateValue: string = null;
@input() public placeholder: string = null;
@input() private format = 'YYYY/MM/DD HH:mm:ss';
get dateValue() {
return moment(this._dateValue, this.format);
}
set dateValue(val) {
this._dateValue = moment(val).format(this.format);
this.propagateChange(this._dateValue);
}
addEvent(type: string, event: MatDatepickerInputEvent) {
this.dateValue = moment(event.value, this.format);
}
writeValue(value: any) {
if (value !== undefined) {
this.dateValue = moment(value, this.format);
}
}
propagateChange = (_: any) => { };
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched() { }
}
`
Thanks!