1

我已经编写了一个 mat-date-picker,并希望从我的 JSON 中输出来自 accountingYearStart 的值。我写了以下代码:

<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
    }
}
4

1 回答 1

1

您的 "fiscalYearStart" 是一个字符串,而 mat-datepicker 需要一个Date 对象,因此您需要对其进行转换。

此外,您的日期不是标准日期,所以我想您可以拥有类似的功能

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)
}

并使用

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

  
于 2020-12-07T11:04:54.220 回答