问题
I am trying to implement a datepicker component with a dynamic name.
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>
where column.name
changes dynamically in my html page.
In runtime I am getting this error:
ERROR TypeError: this._datepicker._registerInput is not a function
Do you have any idea about the cause of this error?
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
Edit: 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
回答1:
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>
This way you can access each element individually via element ref
回答2:
I would like to point out the solution proposed by @yurzui in the comments associated to the question, so it would be visible to everyone:
<div *ngFor="let column of columns">
<input mdInput [mdDatepicker]="startPicker" placeholder="Start {{column.label}}">
<button mdSuffix [mdDatepickerToggle]="startPicker"></button>
<md-datepicker #startPicker></md-datepicker>
</div>
columns = [
{
label: 'column1',
name: 'name1'
},
{
label: 'column1',
name: 'name1'
},
{
label: 'column1',
name: 'name1'
}
]
回答3:
When using dynamic material datepicker in reactive form array, using the index directly clashes with the formGroupName. Using "ii" solved the issue for me.
<div *ngFor="let item of myForm.get('myFormArray').controls; let i = index">
<div [formGroupName]="i">
<mat-form-field>
<input matInput formControlName="myDate" [matDatepicker]="ii" />
<mat-datepicker-toggle matSuffix [for]="ii"></mat-datepicker-toggle>
<mat-datepicker #ii touchUi></mat-datepicker>
</mat-form-field>
</div>
</div>
来源:https://stackoverflow.com/questions/44616888/angular-material-2-datepicker-with-dynamic-name