如何在Angular中动态添加表单控制组?

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

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

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

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

angular angular-forms form-control angular-formbuilder
1个回答
0
投票

我不知道我是否正确理解你的意思。

下面是你如何在你的案例中使用反应式表单。

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>
© www.soinside.com 2019 - 2024. All rights reserved.