0

I have an *ngFor directive. I take the index and I have another class that I want to bind to the inputs inside this *ngFor directive. See the code below:

<div
*ngFor="let plate of plates; index as i;">
<label class="form-control-plaintext"
   for="plate{{i+1}}">{{i+1}}. Plate</label>
<div class="input-group">
<input id="plate{{i+1}}" type="text"
   class="form-control"
   name="plate{{i+1}}"
   [(ngModel)]="car.plate{{i+1}}"/>
</div>
</div>

My problem is that I have 2 fields in Car type:

plate1?: string;
plate2?: string;

and I want to bind to these fields using *ngFor's index like car.plate{{i+1}} Is this possible?

oksuzlerOmer
  • 125
  • 1
  • 2
  • 11

1 Answers1

2

Since car is an object, you can access its properties with []

<input id="plate{{i+1}}" type="text"
  class="form-control"
  name="plate{{i+1}}"
  [(ngModel)]="car['plate' + (i+1)]"/>
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Glad to help :) Also you can check this SO thread out: https://stackoverflow.com/questions/49610238/angular-5-dynamic-variable-name – Harun Yilmaz Mar 29 '19 at 09:25