robert trudel
robert trudel

Reputation: 5749

Assign default value for a date type

I use angular 10. I have a modal with a date input. I would like to assign today date.

In a component, I have

  addEventForm: FormGroup;
  addEventFormInitialValues = {
      eventType: ['', Validators.required],
      eventDate: ['', Validators.required]
  };

In the constructor I tried

  this.addEventFormInitialValues.eventDate = this.datepipe.transform(new Date(), 'yyyy-MM-dd');

I get this error

error TS2322: Type 'string' is not assignable to type '(string | ((control: AbstractControl) => ValidationErrors))[]'.

I also tried

eventDate: [new Date(), Validators.required]

I don't get error but I don't have any default date displayed

<div class="form-group row">
    <label for="eventDate" class="col-sm-3 col-form-label">{{'addEvent.eventDate' | translate}}</label>
    <div class="col-sm-3 self-center">
        <input type='date' id="eventDate" formControlName="eventDate"/>
        <p class="no-bottom-margin">
                <app-form-validation-hint *ngIf="addEventSubmitted && eventAddForm.eventDate.errors && eventAddForm.eventDate.errors.required"></app-form-validation-hint>
        </p>
    </div>
 </div>

Upvotes: 0

Views: 3937

Answers (2)

lbsn
lbsn

Reputation: 2402

The input element with type=date expect the value to be a valid date string in the format yyyy-mm-dd. So this would work:

addEventFormInitialValues = {
    eventType: ['', Validators.required],
    eventDate: [
      '2021-09-02',
      Validators.required
    ]
  };

but obviously it's not very handy to directly deal with dates in string format. You can take a look at this answer for how to format a JS Date as yyyy-mm-dd, but if you expect your application to do something more than trivial operations on dates I suggest you adopt a library such as date-fns.

That being said, note that Angular doesn't come with a built in ValueAccessor for date inputs. When you write this:

eventDate: [new Date(), Validators.required]

your Angular form control gets indeed the default value. The point is, that value is not transcoded to a suitable format for the input element and that's why you don't see it there. Keeping your model date format and display date format in sync will probably require a custom ValueAccessor.

Upvotes: 1

ShayD
ShayD

Reputation: 799

You shuold use the format : 'yyyy-MM-dd'

Example: https://stackblitz.com/edit/angular-ivy-rtp8xl?file=src/app/reactive-form-dates-example.component.ts

Upvotes: 0

Related Questions