Micko
Micko

Reputation: 441

ngModel is reflecting to all textareas

I have multiple textareas (looping with ngFor and adding new divs with textareas inside). What i need is for every textarea to have separate ngModel and i don't want to directly bind this to property from object in dataArray - for example:

[(ngModel)]='data.note' or [(ngModel)]='data.feedback' . 

This works but I don't have feedback property in dataArray so it won't for work for second textarea.

For example with my current implementation change in one textarea is reflecting in all other textareas. I tried with index approach but getting error:

ERROR TypeError: Cannot read property '1' of undefined

<div *ngFor="let data of dataArray; let index=index;trackBy:trackByIndex;">
<div class="card-body">
  <form class="form">
    <div class="form-body">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <textarea name="note" [(ngModel)]='selectedNote' class="form-control"
              rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <textarea name="feedback" [(ngModel)]='selectedFeedback' class="form-control" rows="4"></textarea>
          </div>
        </div>
      </div>
    </div>
  </form>
</div>

With current code if i add some text in first textarea with name 'note' that change is reflected for all textareas with name 'note'. As mentioned tried with adding

[(ngModel)]='selectedFeedback[index]' but i am getting error.

Also tried with giving different names to textareas:

<textarea name="note{{index}}" [(ngModel)]='dataArray[index]' rows="2"></textarea> OR

  <textarea name="note{{index}}" [(ngModel)]='selectedNote' rows="2"></textarea> 

but change is reflecting for each textarea again.

Upvotes: 4

Views: 421

Answers (2)

Debojyoti
Debojyoti

Reputation: 4841

You can try it with any array, I am using data(n) function to return an Array of length n. In this example it's just for iteration

<div *ngFor="let item of data(8); let i = index">
  <textarea [(ngModel)]='values[i]'></textarea>
</div>

// To reflect changes
<div *ngFor="let item of data(8); let i = index">
  <div>{{ values[i] }}</div>
</div>

With TS

export class AppComponent  {

  values = [];

  data(n) {
    return Array(n);
  }
}

Working example in Stackblitz.com

Upvotes: 1

Vivek
Vivek

Reputation: 75

ngModel binds with the name property. So if you want to use multiple textarea try using different name attribute. You can iterate over like -

<ng-container *ngIf="let data of dataArray; index as i">
   <textarea name="feedback_{{i}}" [(ngModel)]='selectedFeedback' class="form-control" rows="4"></textarea>
</ng-container>

Upvotes: 1

Related Questions