在Form |中添加新的输入字段时,动态值会重置Angular 4

时间:2017-10-15 23:31:14

标签: javascript forms angular typescript

我有一个带有电话字段的表单,当您单击“添加”按钮时,将出现一个新字段。发生的事情是,当我单击Add时,先前字段中键入的值将被重置。我设法通过删除“表单”标签使其工作,但我需要在我的项目上使用此表单。如何使用“表单”使其工作?

HTML

<form>
   <div *ngFor="let phonecount of phonecount; let i = index" class="form-group">
<label>Optional Phone </label>
<input type="text" class="form-control" [(ngModel)]="user.extraphones[i]" name="phone2">
 </div>
<input (click)="onSubmito()" type="submit" value="Add" class="btn btn-primary">
</form>

TS

user = {
          name:'',
          phone:'',
          extraphones:[]
      };
  namee='';
   phonecount:string[]=[''];
onSubmito(){
  this.phonecount.push(this.namee);
}

Punkler:https://plnkr.co/edit/i85x1m?p=preview

1 个答案:

答案 0 :(得分:2)

确保你绑定到正确的东西。同样,当使用点击“添加”时,请确保正在更新正确的集合。

在更好地理解您的问题之后,我找到了this SO answerthis GitHub issue

能够解决您的问题......请注意以下事项:

    模板中的
  • trackBy:trackById和打字稿代码中的trackById函数。
  • {li> name属性<input>字段。
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {FormsModule} from '@angular/forms'
import {BrowserModule} from '@angular/platform-browser'

export class Info {
  id: number;
  description: string;
}

    @Component({
      selector: 'my-app',
      template: `
      <form>
       <div *ngFor="let ph of user.extraphones; let i = index; trackBy:trackByIndex" class="form-group">
        <label>Optional Phone</label>
        <input type="text" class="form-control"
          [(ngModel)]="user.extraphones[i]" name="item-{{i}}">
      </div>
      <input (click)="onSubmito()" type="submit" value="Add" class="btn btn-primary">
    </form>

      {{ user.extraphones | json }}
      `,
    })
    export class App {
      user = {
              id:'',
              _id:String,
              name:'',
              phone:'',
              extraphones:['123', '345', '678'],
              rank:''
          };

      namee='';

      onSubmito(){
        this.user.extraphones.push(this.namee);
      }

      trackByIndex(index: number, value: number) {
        return index;
      }
      }
    }

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}