0

I'm trying to dynamically build a number of datepickers from Angular Material.

The sample code given in Angular Material is like this:

<input [matDatepicker] = "myDatepicker">
<mat-datepicker-toggle [for] = "myDatepicker"></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>

Now my issue is that I want to wrap this whole code block in an *ngFor and let it repeat a number of times. Therefore instead of #myDatepicker I name it #myDatepicker{{i}} where i is the index of the *ngFor loop. My issue is now how do I put that index i in the [for] = "myDatepicker" part?

I have tried [for] = "myDatepicker{{i}}" which gives an error:

Template parse errors: Parser Error: Got interpolation({{}}) where expression was expected.

I have also tried for = "myDatepicker{{i}}" but that doesn't seem to work either even though no error.

ysf
  • 4,634
  • 3
  • 27
  • 29
Megan Tan
  • 9
  • 1

2 Answers2

0

Currently, there is no direct support for that, only some workarounds. This feature has been requested by community - https://github.com/angular/angular/issues/33233 and you can find some solutions around it on other member's question on Stack Overflow - Dynamic template reference variable inside ngFor (Angular 2)

Both links provide some solutions, but indeed I think it's a missing feature.

ease
  • 51
  • 5
0

You don't need to worry about that in order for the pickers to work properly. Angular will automatically figure out which picker is which based on DOM scope. So the following would work just fine:

<div *ngFor="let i of [0,1,2]">
  <mat-form-field>
    <input [matDatepicker] = "myDatepicker">
    <mat-datepicker-toggle [for] = "myDatepicker"></mat-datepicker-toggle>
    <mat-datepicker #myDatepicker></mat-datepicker>
  </mat-form-field>
</div>
G. Tranter
  • 16,766
  • 1
  • 48
  • 68
  • Actually I'm asking this question because when I choose a date, it changes the value of the next datepicker instead of this one. I found a hack by setting the input's to have [(ngModel)] with an array, and setting the next value to null. – Megan Tan May 14 '20 at 00:07
  • Post _all_ your code - not just the snippet. As I said, the example works just fine. Maybe your code has a mistake. – G. Tranter May 14 '20 at 20:22