问题描述
在*ngFor
中使用mat-datepicker
时会遇到此问题.
This issue faced when using mat-datepicker
inside *ngFor
.
mat-datepicker
需要模板引用变量#test
才能绑定到input
.
通常,在内部*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.
没有*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>
但是由于模板reference variables
对于整个模板必须是唯一的,因此当在*ngFor
中重复上述块时,您不能直接将mat-datepicker
用于场景,因此test
并不是唯一的.
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.
推荐答案
您可以在ngFor中添加索引变量,并将该索引的值分配为datepicker的标识符.您还可以在组件内部创建一个值的公共数组,这些值的含义类似于["dtPickerOne","dtPickerTwo"],然后将其用作值.
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>
这篇关于* ngFor中的mat-datepicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!