具有动态名称的Angular Material 2 Datepicker [英] Angular Material 2 Datepicker with dynamic name
问题描述
我正在尝试使用动态名称实现datepicker组件.
I am trying to implement a datepicker component with a dynamic name.
我正在使用Angular 4在基于Angular Material 2的项目中进行开发,这是我的实现:
I am developing in an Angular Material 2 based project with Angular 4, and this is my implementation:
<input mdInput [mdDatepicker]="'start' + column.name + 'Picker'" placeholder="Start {{column.label}}" formControlName="start{{column.name}}">
<button mdSuffix [mdDatepickerToggle]="'start' + column.name + 'Picker'"></button>
<md-datepicker #start{{column.name}}Picker></md-datepicker>
其中column.name
在我的html页面中动态变化.
where column.name
changes dynamically in my html page.
在运行时出现此错误:
ERROR TypeError: this._datepicker._registerInput is not a function
您是否知道此错误的原因?
Do you have any idea about the cause of this error?
注意:用mdDatepicker
和mdDatepickerToggle
属性中的静态值替换column.name
可解决此问题,但我的目标是使用动态值运行此代码
Note: Replacing column.name
with a static value in the mdDatepicker
and mdDatepickerToggle
properties solves the problem, but my goal is to run this code with a dynamic value
用mdDatepicker
和mdDatepickerToggle
属性中的静态值替换column.name
只是解决了运行时错误.但是只有在所有内容都是静态的之后,日期选择器才会被触发,这意味着即使md-datepicker
中的名称#start{{column.name}}Picker
也必须包含静态值
The replacement of column.name
with a static value in the mdDatepicker
and mdDatepickerToggle
properties just solves the runtime error. But the datepicker won't be triggered until everything is static, which means even the name #start{{column.name}}Picker
in the md-datepicker
has to contain a static value
推荐答案
我相信更好的解决方案是在遍历数组时使用索引
I believe a better solution is to use an index while iterating over the array
<div *ngFor="let column of columns; let i=index">
<input mdInput [mdDatepicker]="i" placeholder="Start {{column.label}}" name="{{column.name}}">
<button mdSuffix [mdDatepickerToggle]="i"></button>
<md-datepicker #i></md-datepicker>
</div>
这样,您可以通过元素ref分别访问每个元素
This way you can access each element individually via element ref
这篇关于具有动态名称的Angular Material 2 Datepicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!