Gaetan56
Gaetan56

Reputation: 609

Angular matDatepicker in Reactive form

I am using a matDatepicker ( https://material.angular.io/components/datepicker/api ) in an Angular reactive form.

I created a stackblitz to replicate my issue https://stackblitz.com/edit/angular-57kwq6?file=src%2Fapp%2Fapp.component.ts

I get an object Competition from the server containing a Date object. This object is mapped to the form. I am trying to initialize the datePicker with the date present in the object but it's not working. Besides, when i select a date and click on Save, it doesn't update my object.

The server is a spring boot application. The Java object is :

import java.io.Serializable;
import java.util.Date;
public class Competition implements Serializable {

    private String id;
    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}

It looks to me i have either an issue serializing the date in json or formatting the date for the datepicker component ?

Upvotes: 2

Views: 1823

Answers (1)

Eliseo
Eliseo

Reputation: 57939

Firstly, if you're using Angular's Reactive Forms, you shouldn't use ngModel:

<input name="myDate" matInput [matDatepicker]="picker3"
  class="form-control" placeholder="Date"  
  formControlName="date">

Secondly, your model's date value should be set to the value of a Date instead of a string:

this.editor = fb.group({ 
  date: [new Date(this.model.date), Validators.required], 
});

Upvotes: 4

Related Questions