angular 5 dropdown retain values

Issue

I am tying to generate some fields on the click of a button. The fields are generated fine but the dropdown in the generated fields are not retaining the values selected. They are pushed to the array but the values are not shown in the form. The code is as follows.

app.component.html


<form #formRef="ngForm">
  <div *ngFor="let test of mytest; let in=index" class="col-sm-3">
      <div class="form-group"  >
        <select  name="fe[in]" class="form-control" [(ngModel)]="test.name" >
          <option  *ngFor="let f of fields" [value]="f">{{f}}</option>
        </select>
        <br>
        <select name="ty[in]" class="form-control" [(ngModel)]="test.type"> 
          <option  *ngFor="let ty of types" [value]="ty">{{ty}}</option>
        </select><br>
        <input type="text" [(ngModel)]="test.placeholder" name="name{{in}}" class="form-control" #name="ngModel" required />
        <br>
        <input type="text" [(ngModel)]="test.values" name="name{{in}}" class="form-control" #name="ngModel" />
      </div>
      <br />
  </div>
  <button [disabled]="!formRef.form.valid" (click)="add([in])">Add input</button>
</form>
<br />
<br />
{{ mytest | json}}

app.component.ts


import { Component } from "@angular/core";
import { test } from './test';

  @Component({
  selector: "app-root",
  templateUrl: './app.component.html'
})
export class AppComponent {
  mytest: test[] = [];
  fields: string[] = ['First Name','Last Name','Email Address','Address1 ','Address2 ','City','Postal Code','Province']
  types: string[] = ['text','email','password','dropdown','radio button','check boxes'];

  add(val) {

    this.mytest.push({name: '',type: '',placeholder:'',values:''});

  }
}

Solution

Has to do with the control name:

<select name="ty[in]"

change this to: e.g.

<select [name]="'f' + in"

stackblitz

Answered By – Marcel Hoekstra

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.