在“FormGroup”中预填充输入字段 - Angular2

2024-05-20

我正在使用 Angular2 - 反应形式。一切正常,直到我想在表单中的字段之一中显示预填充的值。

设想:页面上有多个按钮,每个按钮都会打开一个表单,其中的字段如下

  1. Name
  2. Email
  3. Message
  4. 产品代码 --> 此值应根据服务中的每个项目代码预先填充。

失败场景:产品代码输入值变为空。

TS Code:

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>

我怎样才能做到这一点?


UPDATE:正如我们发现的,您需要一个formArray而不是单个formControl。因此,在构建表单时声明:

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

您可以使用setValue or patchValue当您收到数据时,您可以迭代响应并将值修补到表单数组中。称呼patchValues-回调中的方法(订阅)。

patchValues() {
  const control = <FormArray>this.queryForm.get('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 (即索引):

<div formArrayName="arrayOfData">
  <div *ngFor="let code of queryForm.get('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>


原答案:

您应该始终在组件中设置表单值,而不是在模板中。您可以使用patchValue or setValue,当您从服务收到值时...因此您可以在回调(订阅)内执行此操作:

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

那么你不需要使用[value]="item.productCode"在您的表单中,该值是通过表单控件设置的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在“FormGroup”中预填充输入字段 - Angular2 的相关文章