Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding index from *ngFor to [(ngModel)] in Angular (v4)

Tags:

angular

I am using ngFor to iterate through an array and I need to bind the index to ngModel so that each input pair has an individual ID but I don't understand how I pass this in.

Here it is on plnkr: http://plnkr.co/edit/Q8NfhTL25Y8gOoGMXiP2?p=preview

Below is my current code:

  <div class="container">
    <div *ngFor="let question of questions; let i = index" class="row container-generic">
      <div class="col-md-8">
        <div class="container-input-checkbox">
          <label class="container-flex">
            <input class="pvq-create-checkbox" type="checkbox" name="" value="" [(ngModel)]="needsUniqueID"> 
            <div class="pvq-create-label">
              <p>{{ question }}</p>
            </div>
          </label>
          <label [@hideShow]="needsUniqueID ? 'active' : 'inactive'">Answer
            <input type="textbox" name="">
          </label>
        </div>
      </div>
    </div>
  </div>
like image 280
Dachan Avatar asked Dec 15 '25 05:12

Dachan


1 Answers

I would use the template reference variable (with index) for this instead of two-way-binding and change inactive and active to false and true for the animations. So your input would look like this:

<input type="checkbox" name="{{i}}" #name="ngModel" ngModel> 

which now makes the unique name.value (based on index) to be true or false based on the state of the checkbox.

Therefore change [@hideShow] to:

<label [@hideShow]="name.value ? 'true' : 'false'">Answer
  <input type="textbox" name="">
</label>

and in the component, replace inactive with false and active with true and you'll get your desired results :)

Here's your forked PLUNKER.

like image 103
AT82 Avatar answered Dec 16 '25 21:12

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!