Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

data binding - Angular2 ngModel inside of ngFor

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

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

But this didn't work as expected because when I log the words variable it show an empty array as initialized in my Component class. Also, I log the variable from another component should that supposed to be the issue for my problem. I have two components:

  • The form component that contains an array of query components.
  • The query child component that has an array of words strings.

So, the words variable is declared into the queries component but I am logging this variable through the form component like this:

console.log(JSON.stringify(this.queries));

While queries is an array of Query in the form component:

queries:Query[] = [];

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...