【问题标题】:how to add form control group dynamically in angular如何以角度动态添加表单控制组
【发布时间】:2020-05-09 17:39:17
【问题描述】:

我是 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】:

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

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

    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>
    

    【讨论】:

    • 这里我需要添加两种类型的添加和删除,一种用于productId,另一种用于数量权重。有没有其他简单的方法?我可以解决这个问题。这样在 UI 中用户就不会感到困惑了
    • 据我了解,您需要两个字段的数组。所以是的,你需要处理这两种情况。当然,如果你不想重复自己,你可以创建辅助方法。
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2020-03-06
    • 2016-01-28
    • 2018-08-11
    • 2021-05-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多