7

I am new to Angular/Angular Material.

I have a div with 2 MatDatePicker input fields:

<div class="docs-example-viewer-body">
  <mat-form-field>
    <mat-select placeholder="Employee" [(ngModel)]="selectedEmployeeId" name="employee_name" (ngModelChange)="setSelectedEmployee($event)">
      <mat-option *ngFor="let employee of employees" [value]="employee.id">
        {{employee.name}}
      </mat-option>
    </mat-select>
  </mat-form-field>

  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a start date" [(ngModel)]="inputStartDate">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker [startAt]="startDate"></mat-datepicker>
  </mat-form-field>

  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose an end date" [(ngModel)]="inputEndDate">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker [startAt]="endDate"></mat-datepicker>
  </mat-form-field>


  <p *ngIf="selectedEmployeeId"> Selected value: {{selectedEmployeeId}} from {{inputStartDate}} until {{inputEndDate}}</p>
</div>

But I get the following error in the browser:

MatDatepicker can only be associated with a single input. at MatDatepicker._registerInput (datepicker.es5.js:1281) at MatDatepickerInput.registerDatepicker (datepicker.es5.js:1560)

Thanks for your solutions or feedback

Joost

1
  • 2
    Yay, I just made this mistake. picker needs to be unique between the two, try [matDatepicker]="picker1" and [matDatepicker]="picker2" or similar, so long as they're unique. The [for] binding will also need to match the new id. Oct 14, 2017 at 6:50

1 Answer 1

20

The instance variable name needs to be unique to each instance. In the example, I've used picker1 and picker2 but feel free to use better names. Here's a sample from the Material plunker.

<mat-form-field>
  <input matInput [matDatepicker]="picker1" placeholder="Choose a start date" [(ngModel)]="inputStartDate">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1 [startAt]="startDate"></mat-datepicker>
</mat-form-field>

<mat-form-field>
  <input matInput [matDatepicker]="picker2" placeholder="Choose an end date" [(ngModel)]="inputEndDate">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2 [startAt]="endDate"></mat-datepicker>
</mat-form-field>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.