Search code examples
angularangular-ngmodel

How to use the index of ngFor in ngModel angular 2


<div class="row hidden" *ngFor="let q of qu ;let i = index">
  <div class="col-md=12">
    <h2><span class="label label-info"> {{q.ques}}</span></h2>
    <input type="radio" name="answer1" [(ngModel)]="'answer'+i" value="{{q.name}}">FOUR
    <input type="radio" name="answer1" [(ngModel)]="'answer'+i" value="Six">SIX
  </div>
</div>

Controller 

answer0:string;

How to dynamically binf the index to my ngModel.


Solution

  • You can't use [] and {{}} together, either one or the other. ({{}} is for string interpolation only and the result is always as string)

    In the component provide a getter for this

    get self() {
      return this;
    }
    
    [(ngModel)]="self['answer'+i]"