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