ernerock
ernerock

Reputation: 582

Angular2 Dynamic form displaying incorrect ngModel data

Im generating a table and form to edit each field but when I try to edit it, the data displayed in the input fields is incorrect.

HTML

        <form (ngSubmit)="onEditSubmit()">
        <span>What the form gets</span>
        <div *ngFor="let k of keys; let i = index" class="form-group row">
          <span>{{k|uppercase}}</span>
          <div class="col-md-9">
            <input [(ngModel)]="updateModels[keys[i]]" type="text" name="text-input" class="form-control" placeholder="{{k}}" />
          </div>
          </div>
          <button>Submit</button>
          </form>

JS

public data: any = [{id: 1, code1: "VALUE1", code2: "VALUE2", code3: "VALUE3"},{id: 2, code1: "TEST1", code2: "TEST2", code3: "TEST3"}];
public keys: any = ["code1","code2","code3"];
public activeRoleId = '';
public updateModels: any = {};


public toEditData: any = "";
public editedData: any = "";

constructor() {
}

onEditSubmit() {
  this.editedData = this.updateModels;
}

/*CLick on element actions*/
editElement(item): void {
    for (let i = 0; i < this.keys.length; i++) {
        this.updateModels[this.keys[i]] = item[this.keys[i]];
    }
    console.log(this.updateModels);
    this.toEditData = this.updateModels;
    this.activeRoleId = item.id;
}

Plunker

Upvotes: 1

Views: 67

Answers (1)

AVJT82
AVJT82

Reputation: 73377

This error is caused because of you are using a form. If you'd remove the form tags, this would work as you want. BUT, since you are using a form, each name-attribute has to be unique, so that these fields are evaluated as separate form fields.

So the solution for your problem is quite simple, just assign an unique name to your fields, you can make use of the index, so change:

name="text-input" 

for example to the following:

name="text-input{{i}}" 

Then it works like a charm! :) Here's the forked

Plunker

Upvotes: 2

Related Questions