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.

2
  • 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, stackoverflow.com/questions/57185576/… Commented Aug 1, 2019 at 9: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. Commented Aug 1, 2019 at 15:29

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.