tprieboj
tprieboj

Reputation: 1703

Angular generate dynamic FormGroup with custom formControlName

I want to create a dynamic formGroup based on json like this:

  const LIMITS: Limit[] = [
  {
    id: 'limit1',
    value: 1000,
    disabled: false
  },
  {
    id: 'limit2',
    value: 500,
    disabled: true
  },
  {
    id: 'limit3',
    value: 5000,
    disabled: true
  }
]

Using formArray from this response works fine, but I will lost my id information which I need to match edited values. Is there way how to generate dynamic form with my custom formControlName name? Here is stackblitz ecample based on this response.

EDIT


I used approach with FormGroup w but on init I get an errors

Error: Cannot find control with path: 'limits -> limit1'
Error: Cannot find control with path: 'limits -> limit2'
Error: Cannot find control with path: 'limits -> limit3'

I know that when inputs are See this stackblitz example.

EDIT


I have found solution by defining limits then used setControl in data subscription.

 ngOnInit() {
    this.form = this.fb.group({
      limits: this.fb.group({})
    })

    this.limits$.subscribe((limits: Limit[]) => {
      this.form.setControl('limits', this.addLimits(limits));
    });

  }

See stackblity example

Upvotes: 0

Views: 229

Answers (1)

Guerric P
Guerric P

Reputation: 31835

If you want to use the id field as a key, then simply use FormGroup instead of FormArray, and use addControl and removeControl instead of push and removeAt to keep your form dynamic.

Upvotes: 1

Related Questions