简体   繁体   中英

How to create dynamic formGroup in angular

I am trying this for the first time to create dynamic formgroup in Angular reactive forms.

I have an API call and I am getting response object. Based on object name key I want to create a FormGroup name.

Example:-

[
 {
  "LicenseName": "Shop license",
  "LicenseTypeID": "D98B196D668"
 },
 {
  "LicenseName": "Product license",
  "LicenseTypeID": "B98L00D098"
 }
]

So I want to create dynamic formGroup with license name. Right now I am hard coding it.

this.Shoplicense = new FormGroup({
      LicenseNumber: new FormControl('', [Validators.required]),
      DOE: new FormControl('', [Validators.required]),
    });

this.Productlicense = new FormGroup({
      LicenseNumber: new FormControl('', [Validators.required]),
      DOE: new FormControl('', [Validators.required]),
    });

get shoplicenseInfo() {
    return this.Shoplicense.controls;
  }
  get productlicenseInfo() {
    return this.Productlicense.controls;
  }

Any other way to capture data into these form?

Like with real arrays, you can only push onto an array. Therefore, add a FormArray to an FormGroup which will receive one FormControl per dataChunk from your API Call.

  1. Create your FormGroup containing a FormArray

     this.formGroup = new FormGroup({ licenses: new FormArray([]) })
  2. After receiving the data, store it into an Array

     const data: Array<{LicenseName: string, LicenseTypeID: string}> = [];
  3. Iterate over your data, adding a FormControl per call

     data.forEach(dataChunk => this.formGroup.addControl(dataChunk.LicenseName, new FormControl(dataChunk.LicenseTypeID)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM