4

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

4
  • Do you see an error message in the console? Commented Feb 25, 2018 at 20:18
  • can you try to provide your code on stackblitz? Commented Feb 25, 2018 at 22:37
  • @ConnorsFan: No, I didn't see any error Commented Feb 26, 2018 at 4:28
  • @davecar21: stackblitz.com/edit/angular-pvqugs Commented Feb 26, 2018 at 5:10

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

my json response is sending string date, I have converted string to date, But still not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.