首页 > 解决方案 > 如何以角度动态添加表单控制组

问题描述

我是 Angular 新手,我正在根据我的要求使用表单控件添加一些字段。我需要动态添加一些包含数组的字段。但我不知道如何在 UI 中向用户展示这种功能。请帮助实现这一目标。这是示例 JSON

{
  "city": "hyderabad",
  "comboDesciption": "ioioioyio",
  "label": "combo", 
  "price": 650,
  "productIds": "Mutton Liver,Chicken",
  "qtyIds": "500gm,700gm"
}

在上面的 JSON 中,我有 productIds,我需要为一个组合选择多个产品,并且它们各自的数量权重在 qtyIds 中引用。请建议我如何在数组中添加我的表单控制组来实现这一点

标签: angularangular-formsform-controlangular-formbuilder

解决方案


我不确定我是否理解正确。

以下是在您的案例中如何使用反应式表单:

myForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit(): void {
 this.myForm = this.fb.group({
   city: [null, Validators.required),
   comboDescription: [null, Validators.required),
   label: [null, Validators.required),
   price: [null, [Validators.required, Validators.min(1)]),
   productsIds: this.fb.array([], Validators.required),
   qtyIds: this.fb.array([], Validators.required)
 })
}

// create getters to retrieve the form array controls from the parent form group
public get productsIds(): FormArray {
  return this.myForm.get('productsIds') as FormArray;
}

public get qtyIds(): FormArray {
  return this.myForm.get('qtyIds') as FormArray;
}

// create methods for adding and removing productsIds
public addProduct(): void {
  this.productsIds.push(this.fb.control('', [Validators.required]));
}

public removeProduct(index: number): void {
  if(this.productsIds.length < 1) {
   return;
 }

  this.productsIds.removeAt(index);
}

// do the same for the qtyIds

在模板中:

<form [formGroup]="myForm">
  .
  .
  .
  // example for productsIds
  <div formArrayName="productsIds">
    <button (click)="addProducts()">Add Product</button>

    <div *ngFor="let productId of productsIds.controls; index as i">
      <input type="text" [formControlName]="i">
      <button (click)="removeProduct(i)">Remove Product</button>
    </div>
  </div>
  .
  .
  .
</form>

推荐阅读