NOTE: This first part is NOT for your problem. In general, when you need a form must be like
form=new FormGroup({
name:new FormControl(),
allowedFields:new FormArray([]);
})
So make three function and a getter and declare a variable form:
form:FormGroup;
get allowedFields()
{
return this.form.get('allowedFields') as FormArray;
}
getForm(data:any)
{
data=data||{data:null,allowedFields:[]}
return new FormGroup({
name:new FormControl(data.name),
allowedFields:new FormArray(data.allowedFields.map(x=>new FormControl(x)))
})
}
addAllowedField(data:string)
{
this.allowedFields.push(new FormControl(data));
}
removeAlloedField(index)
{
this.allowedFields.removeAt(index)
}
Your .html
<form [formGroup]="form" (submit)="submit(form)">
<input formControlName="name">
<div formArrayName="allowedFields">
<button type="button" (click)="addAllowedField(null)">add</button>
<div *ngFor="let control of allowedFields.controls;let i=index" >
<input [formControlName]="i">
<button type="button" (click)="removeAllowedField(i)">remove</button>
</div>
</div>
<button type="submit">submit</button>
</form>
See that you write <div formArrayName="allowedFields"> and iterate over allowedFields.controls -is the "getter" defined in .ts. To control the "input" you can use [formControlName]="i" (or [formControl]="control" -control is the variable of the *ngFor
THIS PART is your about your QUESTION
But you want a series of checkbox and send and array with the values selected, so your form it's only two field
form=new FormGroup({
name:new FormControl(),
allowedFields:new FormControl();
})
See that "allowedFields" is a FormControl, NOT a FormArray.
A suppose you has an array of "allowedFields", make it an array of object, e.g.
fieldList=[
{id:1,name:"field one"},
{id:2,name:"field two"},
{id:3,name:"field three"},
]
We are going to use inputs that not belong to the formGroup, yes [(ngModel)] in a ReactiveForms
<form [formGroup]="form" (submit)="submit(form)">
<input formControlName="name">
<div *ngFor="let item of fieldList;let i=index" >
<input type="checkbox"
[ngModel]="item.check"
(ngModelChange)="item.check=$event;setAllowedFields()"
[ngModelOptions]="{standalone:true}"
>{{item.name}}
</div>
<button type="submit">submit</button>
</form>
And a function
setAllowedFields()
{
this.form.get('allowedFields').setValue(this.fieldList
.filter(x=>x.checked)
.map(x=>x.id))
}
See stackblitz
Update for prepopulate the checks, as always, we has a function to return the formGroup
getGroup(data)
{
data=data || {name:'',allowedFields:[]}
//prepopulate the data
this.fieldList.forEach(x=>{
x.check=data.indexOf(x.id>=0)
})
/* //or
allowedField.forEach(x=>{
const field=this.fieldList.find(f=>f.id==x)
if (field)
field.check=true;
})
*/
return new FormGroup({
name:new FormControl(data.name),
allowedFields:new FormControl(data.allowedFields);
})
}
You use as
this.form=this.getGroup(null) //<--a empty form
this.form=this.getGroup(data) //<-- a form with data