Angular Material 2 Datepicker with dynamic name

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 23:13:16

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

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'
    }  
]

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!