Angular2: Input Controls will lose value inside the form tag with ngFor

I designed a page in Angular2 that uses a form tag, and I displayed input controls using ngFor in the table tag.

I created a model (DataModal) to represent each row of the table. I created a list of models (DataModalList) and continued to add each model to it when I clicked the button (addNewRow)

I ran into the problem of deleting selected input values ​​when adding a new line. Everything works fine when I removed the form tag. I need a form tag to perform validation.

Code below:

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>
+4
1

html.

index-i name. :

<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>
+2

Source: https://habr.com/ru/post/1665879/


All Articles