Jayakrishnan
Jayakrishnan

Reputation: 4294

Angular2: Input Controls losses value inside form tag with ngFor

I have developed a page in Angular2 which uses form tag and I have rendered input controls using ngFor in table tag.

I have created model (DataModal) to represent each row of table. I have created list of model (DataModalList) and kept adding each model into it on click of button (addNewRow)

I am facing the problem of selected input values getting removed on adding new row. Things are working fine when I removed the form tag I need form tag to perform validations.

Please find below code:

Model:

import {DropDownModel} from '../models/dropDownModel'; 
export class DataModal {
  dropdown: DropDownModel[];
  selectedValue: string;
  constructor() {           
          this.selectedValue = "0";  
      }
 }

Component:

addNewRow() { 
    let dataModal = new DataModal();
    dataModal.dropdown = response; //values are coming from api
    this.DataModalList.push(dataModal);
}

Html:

<form novalidate #form="ngForm" (ngSubmit)="submitEditForm(form.valid)">
    <table>
        <tr *ngFor="let item of DataModalList;let i= index ">
            <td class="col-md-3">
                <div>
                    <label class="control-label" for="BoxID"> Box Number </label>
                    <select class="form-control" #BoxID="ngModel"  name="BoxID" [(ngModel)]="item.selectedValue">
                             <option  value="0" disabled > -- select -- </option>
                             <option *ngFor="let element of item.dropdown"                                                           
                              [value]="element.value" >{{element.label}}</option>
                         </select>
                </div>
            </td>
            <td class="col-md-3">
                <div>
                    <a title="Add" (click)="addNewRow()" class="btn blue btn-sm">
                        <i class="fa fa-plus"></i>
                    </a>
                </div>
            </td>
        </tr>
    </table></form>

Upvotes: 5

Views: 652

Answers (1)

Mansi Kalola
Mansi Kalola

Reputation: 159

Your controls need unique names to work properly in html page.

So use index-i also in name attribute. use below code:

<select class="form-control" #BoxID="ngModel" name="BoxID-{{i}}"
[(ngModel)]="item.selectedValue" [ngModelOptions]="{standalone: true}>
<option  value="0" disabled > -- select -- </option>
<option *ngFor="let element of item.dropdown"                                                           
    [value]="element.value" >{{element.label}}
</option>
</select>

Upvotes: 2

Related Questions