How can I output the content of a JSON in mat-date-picker with GET?

252 views Asked by At

I have written a mat-date-picker and would like to output the value from fiscalYearStart from my JSON. I have written the following code:

<div class="form-group" id="align-date-picker">
                        <mat-form-field appearance="fill" id="optimize-form-field">
                          <mat-label>Datum</mat-label>
                          <label>
                            <input matInput [matDatepicker]="picker" formControlName="fiscalYearStart" required>
                          </label>
                          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                          <mat-datepicker #picker></mat-datepicker>
                        </mat-form-field>
                      </div>
ngOnInit() {
    // To initialize loadData
    this.loadData();
  }

 // Fill the dashboard with data
  loadData() {
    this.userAreaService.getCurrentFiscalYear().subscribe( resp => {
      const fiscalYearStart = resp.success ? resp.mandant.fiscalYearStart : null;
      return fiscalYearStart;
    });
  }
// JSON
{
    "success": true,
    "mandant": {
        "mandantId": 1,
        "firm": "Test1",
        "landLineNumber": "+658978784344",
        "fiscalYearStart": "Dez. 6, 2020" // I want to output this
    }
}
1

There are 1 answers

1
Eliseo On

your "fiscalYearStart" is a string, and mat-datepicker need an Date object, so you need transform it.

Futhermore your date is not a standard date so I imagine you can has a function like

dateStringToDate(string date)
{
   const parts=date.split(' ');
   const year=+date[2]
   const day=+date[1].split(',')[0]
   const month=["Ene.","Feb.","Mar.","Apr.","May.","Jun.","Jul.","Ago.","Sep.","Nov.","Dez."]
          .indexOf(date[1])
   return new Date(year,month,day)
}

and use

.subscribe( resp => {
  const fiscalYearStart = resp.success ? resp.mandant.fiscalYearStart : null;
  myForm=new FormGroup({
      fiscalYearStart:new FormControl(this.dateStringToDate(fiscalYearStart)
  })
});