如何使用 Angular 以数组形式设置值

问题描述 投票:0回答:3

我想像这样在数组中设置值:

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 doesn't work
  this.fData[index].controls[name].setValue('name')
}
onSubmit() {
  this.fData.push(this.buildGroup());
  const {valid, value} = this.fData;
  console.log(valid, value);
}
angular angular-reactive-forms
3个回答
32
投票

对于数组,需要使用

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 || []));

8
投票

这是我在

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

0
投票

如果您收到错误“ERROR Error: Cannot find control with path: '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>

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

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.