0

I have a http post service that wants a date with time in this format:

YYYY-MM-DDTHH:MM:SSZ

In one form now I have a formGroup like this:

this.formBuilder.group({
  name: [''],
  startDate: [null],
})

but in the form I have three input:

<form [formGroup]="myForm">
 <input type="text" formControlName="name">
 <mat-datepicker formControlName="day?"></mat-datepicker>
 <input type="number" formControlName="hour?">
 <input type="number" formcontrolName="minutes?">
<form>

I have a datepicker for select a date, and two inputs for managing hour and minutes. My idea is to convert the formGroup in this way:

this.formBuilder.group({
   name: [''],
   day: [null],
   hour: [null],
   minutes: [null]
})

But the server needs only one field and I would have a clean way to do it...my idea was to create single fields for managing each value and in the submit compose the data in someway or is there another solution?

2 Answers 2

1

Personally - I'd go with creating a separate component that implements the ControlValueAccessor (see docs). It would contain your three inputs, but would work as a single form control (i.e. emitted when any "child" input emits). Then, your form would retain it's "correct" format:

this.formBuilder.group({
  name: [''],
  startDate: [null],
})

And your template would look something like this:

<form [formGroup]="myForm">
 <input type="text" formControlName="name">
 <app-custom-date-picker formControlName="startDate"></app-custom-date-picker>
<form>

I think that would be the most "clean" approach and would allow you to re-use that component across multiple other forms if needed be.

I won't go into the details of how to create your custom form control (i.e. implement ControlValueAccessor as this is covered by multiple greate guides around the web.

Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend to use the Angular Material Datepicker. It works really well with formBuilder: https://material.angular.io/components/datepicker/overview

Check this, stackblitz, where I fill a mat-datepicker with newDate = new Date();:

https://stackblitz.com/edit/angular-oyxsqm?file=src%2Fapp%2Fdatepicker-overview-example.ts

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.