-1

I am using two-way binding in my template driven form:

ts:

searchLeaveApplication: any = {};

html:

<mat-form-field class="searchInputs">
  <input
    matInput
    [matDatepicker]="searchStartDate"
    [(ngModel)]="this.searchLeaveApplication.startDate"
    name="startDate"
  />
  <mat-datepicker-toggle
    matSuffix
    [for]="searchStartDate"
  ></mat-datepicker-toggle>
  <mat-datepicker #searchStartDate></mat-datepicker>
</mat-form-field>

However I am getting this as the date: enter image description here

Which is not acceptable as a date format for the API (.Net core). How can I change to format to the proper date format? I suppose I am not able to use date pipes in two-way bindings.

Efron A.
  • 353
  • 3
  • 10
  • 19

1 Answers1

2

You can always import Angular's DatePipe, or FormatDate into your component.ts, and convert searchLeaveApplication.startDate to the required datetime format that is accepted by .Net core. The full list of pre-defined options and custom formats can be found here.

1) If you are intending to use DatePipe, you may do the following below.

import { DatePipe } from '@angular/common';

export class SampleComponent implements OnInit {   

constructor(private datePipe: DatePipe) {}

  saveData() {
    const searchStartDateString = this.datePipe.transform(this.searchLeaveApplication.startDate, 'yyyy-MM-dd');
    // handle the rest
  }
}

Do not forget to add DatePipe to your providers in your module.

providers: [DatePipe]

2) Alternatively, you may want to use formatDate:

import { formatDate } from '@angular/common';

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  saveData() {
    const searchStartDateString = formatDate(this.searchLeaveApplication.startDate, 'MM-yyyy', this.locale);
    // handle the rest
  }
}
wentjun
  • 40,384
  • 10
  • 95
  • 107