I am using Reactive Forms FormGroup, FormBuilder and FormArray. I have a FormArray in which I would like to loop through an external array, create a list of checkboxes and then pass the id of those checkboxes to my FormArray.
My components typescript looks like:
export class AppComponent {
form: FormGroup;
sites = [ "site-1", "site-2", "site-3", "site-4" ];
constructor(private fb: FormBuilder){
}
ngOnInit() {
this.form = this.fb.group({
type: [ '', Validators.required ],
sites: this.fb.array([
this.fb.group({
siteId: [ '', Validators.required ]
})
])
})
}
}
And my html...
<form [formGroup]="form">
<input type="checkbox" formControlName="type" id="type">
<label for="type">Type</label>
<div class="checkbox-group" style="margin-top:40px">
<div class="checkbox-wrap" id="productsContainer">
<input type="checkbox" id="all">
<label for="all">All mills</label>
<div *ngFor="let site of sites; let i = index">
<input type="checkbox" [id]="i" />
<label [for]="i"> {{ site }} </label>
</div>
</div>
</div>
</form>
I know I need to pass the formArrayName into the html but I am getting console errors when trying to pass in the formArrayName="sites" and then using the "i" from my loop as the formGroupName. What am I doing wrong?
Here's a StackBlitz with the full setup...
https://stackblitz.com/edit/angular-rcfnwi?file=app%2Fapp.component.html
all
option, but that is also not in your question :P :P – AJT82