stackUser44
stackUser44

Reputation: 409

Angular 2 material datepicker ngModel not displaying value

I am new to angular and material 2, I am using material date picker in my form to display and select the date. I am able to select the date and bind to ngModel. But when I try to bind my response to ngModel showing nothing. I have converted my string date to date and then binding to ngModel. Below is the code, Please help me where i am missing.

 <mat-form-field>
  <input matInput id="dateOfBirth" name="dateOfBirth" [matDatepicker]="dateOfBirth" 
          class="form-control" [(ngModel)]="customer.dateOfBirth"
            placeholder="Date of birth" required>
 <mat-datepicker-toggle matSuffix [for]="dateOfBirth"></mat-datepicker-toggle>
          <mat-datepicker #dateOfBirth></mat-datepicker>
          <mat-error>Date of birth is required</mat-error>
        </mat-form-field>

my ts file getting the response from json

   customer: CustomerModel = new CustomerModel();
 this.customerService.getResponse().subscribe(resp => {
           this.customer= resp;
 console.log('Date:'+this.customer.dateOfBirth);// able to print
        });

    Class CustomerModel {
        dateOfBirth: Date; 
         //other customer details
      }

Here I have created sample https://stackblitz.com/edit/angular-pvqugs

Upvotes: 4

Views: 6974

Answers (2)

stackUser44
stackUser44

Reputation: 409

I resolved it, I was converting the string date format and then tried to bind with the ngModel. I removed my format date part(using DatePipe) and converted string to date.

    if (date) {
  let dateOld: Date = new Date(date);
  return dateOld;
    }

Here the updated code https://stackblitz.com/edit/angular-pvqugs

Upvotes: 3

Cristian Sevescu
Cristian Sevescu

Reputation: 1489

On your example from stackblitz, on init, you set the date to a string value, that is not accepted by datepicker component. If you comment ngOnInit method, it will display the value.

Not enough details in the code here to know what type is customer.dateOfBirth. It works fine with type date.

This example from the documentation shows different ways of binding the component, even with a serialized value: https://stackblitz.com/angular/dlerqrdamjl?file=app%2Fdatepicker-value-example.html

Upvotes: 1

Related Questions