5
                <input
                  [value]="question.timestampToMoment(row.controls[column.name].value)"
                  [formControlName]="column.name"
                  [required]="column.required"
                  matInput
                  [matDatepicker]="picker"
                  (dateChange)="question.onDateChange($event)"
                  placeholder="Choose a date"
                />

I would like the FormControl that's attached to this datepicker have the timestamp as the value, so that the timestamp can be sent back to the backend. Then in setting the value of this datepicker when the value comes back from the backend, I would need to convert it back to a moment object from the timestamp.

I imagine timestampToMoment would look like: return moment(value * 1000)

I can't figure out how to implement onDateChange or any other way to make this work though. The datepicker uses moment.js.

gruuuvy
  • 2,028
  • 4
  • 31
  • 52
  • 2
    the most easy is not include the formControl in the mat-Date-picker and use (dateChange) to change the formControl and [value] to show a date . Remember, a FormControl exist indepent of there are a input or not. It's some loks like anohter question, but with a check-box, https://stackoverflow.com/questions/57185576/invert-checked-value-of-a-mat-checkbox/57189478#57189478 – Eliseo Aug 01 '19 at 09:32
  • Ah, thanks. This completely works. I was focused on the idea that the FormControl and the datepicker were one entity. If you add this as an answer I can mark it. – gruuuvy Aug 01 '19 at 15:29

1 Answers1

5

As mentioned in the comments by @Eliseo, the trick here is to not include the FormControl in the datepicker input, and use the dateChange event to manually change the value of the FormControl. The value for the datepicker can in turn be set by passing the timestamp into a function.

<input
  [value]="timestampToMoment(form.controls[key].value)"
  [required]="required"
  matInput
  [matDatepicker]="picker"
  (dateChange)="onDateChange($event, form.controls[key])"
  placeholder="Choose a date"
/>

timestampToMoment(value: number): Moment {
  return moment(value * 1000);
}

onDateChange(event: MatDatepickerInputEvent<any>, control: AbstractControl): void {
  control.setValue(event.value.valueOf() / 1000);
}
gruuuvy
  • 2,028
  • 4
  • 31
  • 52