Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

angular - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...