angular - 在 `FormGroup` 中预填充输入字段 - Angular2

标签 angular angular2-template angular2-forms

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

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

  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。所以在构建表单时声明:

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

您可以在收到数据后使用 setValuepatchValue,在其中迭代响应并将值修补到表单数组。在回调(订阅)中调用 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>


原答案:

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

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

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

关于angular - 在 `FormGroup` 中预填充输入字段 - Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448923/

相关文章:

css - 使用 ng-deep 在全局主题混合中使用主题颜色

Angular 2 管道触发

html - 按钮内图像的动画

angular - 将控件从 Angular 中的组件添加到 html

css - 覆盖默认应用程序图标(SVG 或 Fonticon?)

javascript - 如何从json格式中选择特定的id...?

Angular4模板引用变量赋值

Angular2如何使用默认值设置单选按钮

javascript - Angular 2 : Add validators to ngModelGroup

Angular 2 将焦点放在组件加载的第一个表单字段上