Angular2 ngModel inside of ngFor

前端 未结 3 1397
借酒劲吻你
借酒劲吻你 2020-12-09 05:49

I am trying to bind an array of strings from my inputs, so in the html file I wrote this:

相关标签:
3条回答
  • 2020-12-09 06:07

    Each input tag has to have a unique 'name' attribute defined, as described in:

    Angular2 ngModel inside ngFor (Data not binding on input)

    Here is the corrected code:

    <div *ngFor="let word of words; let in=index" class="col-sm-3">
      <div class="form-group">
        <input type="text" [(ngModel)]="words[in]" name="word{{in}}" class="form-control" [attr.placeholder]="items[in]" required>
      </div>
    

    0 讨论(0)
  • 2020-12-09 06:22

    The problem is with using an array of primitive values (words) in ngFor.

    You can change words to an array of objects like

    words = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}];
    

    and use it like

      <div *ngFor="let word of words; let in=index" class="col-sm-3">
          <div class="form-group">
            <input type="text" [(ngModel)]="words[in].value"  class="form-control" [attr.placeholder]="items[in]" required>
          </div>
      </div>
    

    This might also be solvable using trackBy but I'm not sure.

    0 讨论(0)
  • 2020-12-09 06:26

    Solved this by using the @Input() function and passing the queries array + the query index number. Thank you guys for the support.

    0 讨论(0)
提交回复
热议问题