Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular material io MatDatePicker

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

like image 632
user1593409 Avatar asked Oct 14 '17 06:10

user1593409


1 Answers

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>
like image 178
stealththeninja Avatar answered Oct 30 '22 11:10

stealththeninja