【问题标题】:How to push input values into an array如何将输入值推入数组
【发布时间】:2017-03-01 11:23:52
【问题描述】:

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("");
  }
}

当我点击添加按钮时,会添加一个新输入,但我为第一个输入输入的相同值也适用于第二个输入。谁能帮助我。谢谢。

【问题讨论】:

  • 请提供完整的代码。
  • 你有混合表单控件和 ngmodel 的原因吗?
  • 嗨,AJT_82,我将其包含在验证中。
  • @Daniel 好的,但是为什么不使用表单控件进行验证,因为您已经在使用它们了 :)
  • @Daniel,请提供您的表单组定义

标签: html arrays angular


【解决方案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
      }
    })

【讨论】:

    【解决方案2】:

    如果您想走模型驱动表单的路线,这里有一个示例。但是,如果您有一个简单的表单,使用模型驱动的表单可能会过大。但是,如果您有一个复杂的表格,这将是一个不错的选择。

    这里有表格:

    <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 文件,其中客户将是一个表单数组,您可以在其中推送新的表单控件:

    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

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2020-12-02
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多