Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mat-datepicker inside *ngFor

This issue faced when using mat-datepicker inside *ngFor.

mat-datepicker requires a template reference variable #test in order to bind to the input.
Is there a direct way to take reference variables when using inside *ngFor, in general? I couldn't find a way.

Simple working example without *ngFor

<mat-form-field>
  <input matInput [matDatepicker]="test" placeholder="Enter Date" [(ngModel)]="someDate" name="someDate">
  <mat-datepicker-toggle matSuffix [for]="test"></mat-datepicker-toggle>
  <mat-datepicker #test></mat-datepicker>
</mat-form-field>

But since template reference variables must be unique for the whole template, you can't directly use the mat-datepicker for scenario when the above block is repeated inside an *ngFor, test wouldn't be unique.

Any pointers will be helpful.

like image 615
bitscanbyte Avatar asked Mar 23 '18 14:03

bitscanbyte


2 Answers

I would like to point out that you can use underscore "_" as a separator if you would like to give it a more meaningful name.

Here is a working example with two way model binding.

<div *ngFor="let patient of patients; let i = index;">
  <input matInput [matDatepicker]="patientDueDate_i" placeholder="Due date" 
    [(ngModel)]="patient.dueDate">
   <mat-datepicker-toggle matSuffix [for]="patientDueDate_i"></mat-datepicker-toggle>
   <mat-datepicker #patientDueDate_i></mat-datepicker>   
</div>
like image 86
Talnaci Sergiu Vlad Avatar answered Oct 13 '22 01:10

Talnaci Sergiu Vlad


You could add an index variable to your ngFor and assign the value of that index as an identifier for you datepicker. You could also make a public array of values inside the component that have a meaning like ["dtPickerOne", "dtPickerTwo"] and use those as values.

<div *ngFor="let t of test; let i = index;">
         <input matInput [matDatepicker]="i" placeholder="Choose a date" [attr.id]="dtPicker + i"
         [formControl]="dateFrom">
         <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
         <mat-datepicker #i></mat-datepicker>   
    </div>
like image 24
theriddle2 Avatar answered Oct 13 '22 01:10

theriddle2