如何将输入值推送到数组中

时间:2017-03-01 11:23:53

标签: html arrays angular

HTML:

<span *ngFor="let cust of customs">
   <div  class="custominfobackground col-sm-12">
    <input type="email" id="widget-subscribe-form-email" name="cust{{$index}}" class="form-control required email" [formControl]="form.controls['custominfo']" 
         [(ngModel)] = "cust.value" [ngClass]="{ active: submitted && !form.controls['custominfo'].valid}"  placeholder="Facebook" aria-required="true">
   </div>
</span>

打字稿:

export class Custom {
  customs:any = [];

  constructor(fbld: FormBuilder, http: Http) {
    this.form = fbld.group({
        custominfo: ['',Validators.required],

    });
  }

  showCustomInfo(){
   this.customs.push("");
  }
}

当我点击添加按钮时,会添加一个新输入,但我输入的第一个输入的值也是第二个输入。也可以有人帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

目前还不清楚你要做什么。您正在混合模板驱动形式和模型驱动形式(反应形式)......您必须做出选择。您的问题的答案将取决于此。

模板驱动

<input type="email" (click)="showCustomInfo($event)">
showCustomInfo($event){
   this.customs.push($event.value);
}

模型驱动

this.yourForm.get('yourInput').valueChanges
    .subscribe(data => {
      //do what you want with your data here
      }
    })

答案 1 :(得分:0)

如果你想走模型驱动形式的路线,这里有一个样本。但如果你有一个简单的表格,使用模型驱动的表格可能是过度的。但是,如果你有一个复杂的形式,这将是一个很好的选择。

我在这里有表格:

<form [formGroup]="myForm">
<button (click)="addCustomer()">Add Customer</button>
<div formArrayName="customers">
  <div *ngFor="let cust of myForm.controls.customers.controls; let i = index" >
    <div formGroupName="{{i}}">
    <p>Customer {{i+1}}</p>
      <label>E-mail</label>
      <input formControlName="email" />
      <span *ngIf="!myForm.controls.customers.controls[i].controls.email.valid">Required!</span>
    </div>
    <hr>
  </div>
</div>
<button type="submit">Submit</button>
</form>

但是,如果您对同一个表单控件有多个不同的验证,我会继续使用mickdev的后一个建议,您可以在其中捕获更改并检查验证并显示正确的验证消息。例如,首先检查用户是否输入了电子邮件,然后检查电子邮件是否是有效的电子邮件等。但是如果您只有几个表单验证,您当然可以直接在模板中检查这些错误。这是一个非常好的link,解释了反应形式和验证,基本上我在代码中提到了这一点。

以下是上述表格中的TS文件,其中客户可以使用formarray来推送新的formcontrols:

this.myForm = this.fb.group({
  customers: this.fb.array([
    this.initCustomers()
  ])
});

initCustomers() {
  return this.fb.group({
    email: ['', Validators.required]
  })
}

addCustomer() {
  const control = <FormArray>this.myForm.controls['customers'];
  control.push(this.initCustomers())
}

以下是带有上述代码的demo plunker