角度5下拉保留值

时间:2018-06-09 04:50:06

标签: angular typescript angular5

我想在点击按钮时生成一些字段。生成的字段很好,但生成的字段中的下拉列表不保留选定的值。它们被推送到数组但值不会显示在表单中。代码如下。

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:''});

  }
}

1 个答案:

答案 0 :(得分:0)

与控件名称有关:

<select name="ty[in]"

将此更改为:例如

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

比它有效:https://stackblitz.com/edit/angular-5-dropdown-retain-values?file=src%2Fapp%2Fapp.component.html