预填充输入到"FormGroup"中的输入-Angular2 [英] Pre Populate input filed in `FormGroup` - Angular2

查看:91
本文介绍了预填充输入到"FormGroup"中的输入-Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2-反应形式.一切正常,直到我想在Form的一个字段中显示一个预先填充的值.

I am using Angular2 - Reactive Forms. Everything works fine until i want to show a pre-populated value in one of fields in Form.

场景:页面上有多个按钮,每个按钮都会打开一个表单,其中的字段为

Scenario: There are multiple buttons on a page and each button opens up a form with fields as

  1. 名称
  2. 电子邮件
  3. 消息
  4. 产品代码->此值应根据服务中的项目代码预先填充.

失败情况:产品代码输入值变为空.

Failing Scenario: Product Code input value turns to null.

TS代码:

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
queryForm: FormGroup;
constructor(private _productService: ProductService, fb: FormBuilder) {
    this.queryForm = fb.group({
        'name': [null, Validators.compose([Validators.required, Validators.minLength(5)])],
        'email': [
            null, [Validators.required, Validators.email]
        ],
        'message': [null,Validators.compose([Validators.required, Validators.minLength(5)])],
        'pcode': [
            null
        ],
    })
}

HTML表单:

<div *ngFor="let item of product">
<form action="#" [formGroup]="queryForm" 
 (ngSubmit)="submitForm(queryForm.value)" method="post" 
  novalidate="" class="text-left note" id="f_{{item.productId}}">
    [ .... rest of the fields ...]
    <div class="form-group hidden">
          <input type="hidden " class="form-control " id="pcode " name="pcode" 
        formControlName="pcode" [value]="item.productCode" />
     </div>
     <div class="form-group">
           <button type="submit" class="btn1" [disabled]="!queryForm.valid">Submit</button>
      </div>
</form>
</div>

我该如何实现?

推荐答案

更新:我们发现,您需要的是formArray而不是单个formControl.因此,在构建表单时声明:

UPDATE: As we found out, you are needing a formArray instead of a single formControl. So declare that when you build form:

this.queryForm = this.fb.group({
  arrayOfData: this.fb.array([]) // name a proper name to array
})

当您接收到数据时,可以使用setValuepatchValue,您可以在其中迭代响应并将值修补到表单数组中.在您的回调(订阅)中调用patchValues-方法.

You can use setValue or patchValue when you have received your data, where you iterate the response and patch the values to your form array. Call patchValues-method in your callback (subscribe).

patchValues() {
  const control = <FormArray>this.queryForm.controls.arrayOfData;
  this.items.forEach(x => {
    control.push(this.patchValue(x.first_name, x.pcode))
  })
}

patchValue(name, code) {
  return this.fb.group({
    name: [name],
    pcode: [code]
  })    
}

在您的模板中,迭代formarray并记住要设置formgroupname(即索引):

In your template iterate the formarray and also remember to set the formgroupname (which is the index):

<div formArrayName="arrayOfData">
  <div *ngFor="let code of queryForm.controls.arrayOfData.controls; let i = index">
    <div formGroupName="{{i}}">
      <label>Name: </label>
      <input formControlName="name" /><br>
      <label>Product Code: </label>
      <input formControlName="pcode" /><br>
    </div>
  </div>
</div>

演示


原始答案:

Demo


Original answer:

您应该始终在组件而不是模板中设置表单值.当您从服务接收到值时,可以使用patchValuesetValue ...这样,您可以在回调(订阅)中执行以下操作:

You should always set the form values in the component, not the template. You can use patchValue or setValue, when you have received the value from the service... so you can do this e.g inside the callback (subscribe):

this.myService.getSomeData()
  .subscribe(data => {
     this.item = data;
     this.queryForm.patchValue({pcode: this.item.productCode})
  });

然后,您无需在表单中使用[value]="item.productCode",而是使用表单控件设置此值.

Then you do not need to use [value]="item.productCode" in your form, this value is set with the form control instead.

这篇关于预填充输入到"FormGroup"中的输入-Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆