如何使用angular设置数组形式的值

时间:2017-07-08 14:57:18

标签: angular angular-reactive-forms

我想在数组中设置值,如下所示:

this.form.controls[name].setValue('name')

但是我正在处理数组表单,即使我传递特定数组表单的索引,这也无法正常工作

例如这是我的表单数组,我想要做的是在函数中设置值

user: FormGroup;
  users: FormGroup;

  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.user = this.buildGroup();
    this.users = this.fb.group({
      data: this.fb.array([this.user])
    });
  }
  get fData() {
    return this.users.get('data') as FormArray;
  }
  buildGroup() {
    return this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      account: this.fb.group({
        email: ['', Validators.required],
        confirm: ['', Validators.required]
      })
    });
  }
setValue(index) {
   this.fData[index].controls[name].setValue('name')
  }
  onSubmit() {
    this.fData.push(this.buildGroup());
    const {valid, value} = this.fData;
    console.log(valid, value);
  }

但是this.fData [index] .controls [name] .setValue(' name')这不起作用

3 个答案:

答案 0 :(得分:14)

对于数组,您需要使用setControl。像这样:

    this.productForm = this.fb.group({
        productName: ['', [Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(50)]],
        productCode: ['', Validators.required],
        starRating: ['', NumberValidators.range(1, 5)],
        tags: this.fb.array([]),
        description: ''
    });

    ...

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));

答案 1 :(得分:3)

以下是我在formArray的特定表单控件中手动设置值并为我工作的所有操作。我将formArray命名为bundleDetails

   this.formBuilderObj['bundleDetails'] = 
   this.formBuilder.array([this.createBundleItem()]);

    createBundleItem(): FormGroup {
    return this.formBuilder.group({
     bsku: ['', Validators.required],
     bqty: ['', Validators.required],
     bprice: ['', Validators.required]
    });
   }

设置bsku控件值的方法(从html文件传递索引为[formGroupName]="i")。

   setSku(sku: string, index: number) {
   const faControl = 
   (<FormArray>this.pmForm.controls['bundleDetails']).at(index);
   faControl['controls'].bsku.setValue(sku);
  }

希望这会有所帮助。快乐的编码。

答案 2 :(得分:0)

如果出现错误“错误错误:找不到路径为'addresses-> 0-> addressType'的控件”或类似的错误,则很可能是因为您要传入值,但是html模板是期望值以及控件名称。

要解决此问题,请遍历数组中的每个项目,并根据视图的期望为每个值创建一个新的表单组实例,然后推送到新的数组变量,然后在表单中进行设置。

请参见下面的代码:

var tagsArray = [];
this.product.tags.forEach(product => tagsArray.push(this.fb.group({tag: [product.tag, [Validators.required]]})));
this.productForm.setControl('tags', this.fb.array(tagsArray || []));

像这样引用视图:

<div class="tag" *ngFor="let t of tags.controls; let i = index" [formGroupName]="i" class="mb-2">
      <input type="text" formControlName="tag" placeholder="Tag name" class="primary_input">
       <button mat-icon-button (click)="deleteTag(i)">
           <mat-icon>clear</mat-icon>
       </button>
 </div>

这使您可以加载以前的结果,同时能够添加更多值和验证用户输入。

希望这会有所帮助。