Home > database >  How to bind list of string date to date picker in Angular 14
How to bind list of string date to date picker in Angular 14

Time:07-11

I have list of date of type string (MM/DD/YYYY) and want to achieve two-way data binding. following is the sample code

    <div *ngFor="let batch of trek.batches; let i = index" [attr.data-index]="i">
    <mat-form-field appearance="standard" >
        <mat-label>Date</mat-label>
        <input matInput [matDatepicker]="batchDatePicker" name="batchDate_{{i}}"  [(ngModel)]="batch.date">
        <mat-hint>MM/DD/YYYY</mat-hint>
        <mat-datepicker-toggle matSuffix [for]="batchDatePicker">
        </mat-datepicker-toggle>
        <mat-datepicker #batchDatePicker></mat-datepicker>
    </mat-form-field>
</div>

batch.date has the date in string form (MM/DD/YYYY)

I have tried to implement following solution but don't know how to achieve two-way data bind with it as I have list of dates in the string format. https://material.angular.io/components/datepicker/overview#datepicker-value

/** @title Datepicker selected value */
@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  date = new FormControl(new Date());
  serializedDate = new FormControl(new Date().toISOString());
}

CodePudding user response:

You need convert your string in a Date object. Generally you use map in service to return the elements with the "date property" convert To Date

getList()
{
   return this.httpClient(...).pipe(
      map((res:any[])=>{
          res.forEach(x=>{
            parts=x.date.split('/')
            x.date=new Date(parts[0] "-" parts[1] "-" parts[2])
          })
          return res;
      })
}
getData(id:any)
{
   return this.httpClient(...).pipe(
      map((res:any)=>{
          parts=x.date.split('/')
          x.date=new Date(parts[0] "-" parts[1] "-" parts[2])
          return res;
      })
}

Analogous, when you receive the data first transform the "date" to your string

update(element:any)
{
    const elementSend={...element}
    elementSend.date= ('00' element.date.GetDate()).slice(-2) "/" 
                      ('00' element.date.GetMonth()).slice(-2) "/" 
                       element.date.GetFullYear() "/"

    this.httpClient.post(...,elementSend)
}
  • Related