简体   繁体   中英

Angular 4 template reference variables

is it possible to have a dynamic template reference variable?

for example, i would like to do something like this:

 <tr *ngFor="let item of items.controls; let i=index" >
  <th >{{i}}</th>
  <td>

    <mat-form-field>
      <input matInput matDatepicker="{{'pick'+i}}" placeholder="date" 
      formControlName="date">

      <mat-datepicker-toggle matSuffix for="{{'pick'+i}}">
      </mat-datepicker-toggle>

      <mat-datepicker #"{{'pick'+i}}"></mat-datepicker>

    </mat-form-field>

  </td>
 </tr>

I am trying to figure out how to write <mat-datepicker #"{{'pick'+i}}"></mat-datepicker> such that the reference variable is dynamic with the loop index. Using interpolation here just to explain what I am trying to achieve.

regards Adisa

Template reference variable inside embedded view(*ngFor) has its own scope so you can just use the same name:

<tr *ngFor...>
    ...
    <mat-form-field>
      <input matInput [matDatepicker]="pick" placeholder="date" formControlName="date">
      <mat-datepicker-toggle matSuffix [for]="pick"></mat-datepicker-toggle>
      <mat-datepicker #pick></mat-datepicker>
    </mat-form-field>

Example

Template reference variables cannot be named dynamically. They must be statically analysable

Have a look here where you have other suggestions on reaching the goal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM