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

问题描述

*ngFor 中使用 mat-datepicker 时遇到的这个问题.

mat-datepicker 需要模板引用变量 #test 以绑定到 input.
通常,在 *ngFor 内部使用时,是否有直接获取引用变量的方法?我找不到办法.

没有*ngFor

的简单工作示例

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

但是由于模板引用变量对于整个模板来说必须是唯一的,当上面的块在一个模板中重复时,你不能直接使用mat-datepicker*ngFor, test 不会是唯一的.

任何指示都会有所帮助.

解决方案

您可以向 ngFor 添加一个索引变量,并将该索引的值指定为日期选择器的标识符.您还可以在组件内部创建一个公共值数组,其含义类似于 ["dtPickerOne", "dtPickerTwo"] 并将它们用作值.

<input matInput [matDatepicker]="i" placeholder="选择日期" [attr.id]="dtPicker + i"[formControl]="dateFrom"><mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle><mat-datepicker #i></mat-datepicker>

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.

解决方案

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:37