I'm building a simple reactive form. For simplicity, lets say the only data I want to display is a date.
test.component.html
<form novalidate [formGroup]="myForm">
<input type="date" formControlName="date">
</form>
test.component.ts
private date: Date = Date.now();
ngOnInit() {
this.myForm = this.fb.group({
date: [this.date, [Validators.required]]
});
}
The input type=date field on the template requires the date to be in the format of 'yyyy-MM-dd'. The value in event is a JavaScript Date object.
How can I modify the data at the template level so the input value is correct?
What I've tried:
One way to do this would be to inject the DatePipe into my component and apply the conversion in code.
date: [datePipe.transform(this.event.date, 'yyyy-MM-dd'), [Validators.required]]
But this ties the implementation detail of the template to the component. For example, what if a NativeScript template requires the date to be in the format MM/dd/yyyy
? The formGroup is no longer valid.
The only way I've been able come up, with the help of @n00dl3 is to wrap the md-input component and provide the proper value via a ControlValueAccessor
import { Component, Input, ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DatePipe } from '@angular/common';
import { MdInput } from '@angular/material';
@Component({
selector: 'md-date-input',
template: `
<md-input [placeholder]="placeholder"
type="date"
(change)="update()"
[value]="dateInput">
</md-input>`,
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: DateInputComponent, multi: true }]
})
export class DateInputComponent implements ControlValueAccessor {
@Input() placeholder: string;
@ViewChild(MdInput) mdInput: MdInput;
dateInput: string;
onChange: (value: any) => void;
constructor(private datePipe: DatePipe) {
}
writeValue(value: any) {
this.dateInput = value == null ? '' : this.datePipe.transform(value, 'yyyy-MM-dd');
}
registerOnChange(fn: (value: any) => void) {
this.onChange = fn;
}
registerOnTouched(fn: (value: any) => void) {
}
update() {
this.onChange(this.mdInput.value ? new Date(this.mdInput.value) : '');
}
}