Angular - add dynamically created FormControls into the FormGroup

3.8k views Asked by At

I have a list, simple - string[]. I generate checkbox for every item of that list. Then I create FormControls:

this.list.map((item) => {
  this.form.addControl(item, new FormControl(false, Validators.required))
})  

But I want to add a Validator to control the allowed number of checked checkboxes, so I assume I could do this if I move those FormControls into the FormGroup, so I try something like:

  constructor(private fb:FormBuilder) { 
        this.form = this.fb.group({
          input1Ctrl: ['', Validators.required],
          input2Ctrl: ['',Validators.required],
          checkboxGroup : new FormGroup({})   
        })         
        this.list.map((item) => {
          this.form.checkboxGroup.addControl(item, new FormControl(false, Validators.required))
        })  

But that gives:

Supplied parameters do not match any signature of call target. Property 'checkboxGroup' does not exist on type 'FormGroup'.

How should I do it?

2

There are 2 answers

3
Amit Chigadani On

Access checkboxGroup like this.form.controls['checkboxGroup'].

  constructor(private fb:FormBuilder) { 
            this.form = this.fb.group({
              input1Ctrl: ['', Validators.required],
              input2Ctrl: ['',Validators.required],
              checkboxGroup : new FormGroup({})   
            })         
            this.list.map((item) => {
              this.form.controls['checkboxGroup'].addControl(item, new FormControl(false, Validators.required))
            })

EDIT : Created plunker for the above

https://plnkr.co/edit/nxo52y?p=preview

0
Ben Racicot On

You're using FormGroup here not formBuilder's group method.

It seems you would set it up like:

this.form = this.fb.group({
   checkboxGroup: this.fb.group({})
})

Accessing FormBuilder's group and FormGroup both work for me like: this.form.get('checkboxGroup') and `this.form.controls['checkboxGroup']

See https://angular.io/api/forms/FormBuilder#control