本文介绍了* ngFor中的mat-datepicker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 22:38