Reputation: 427
I have 7 checkboxes in my RactiveForm
. This is how I am generating them using FormArray
:
ts:
weekDaysDe: string[] = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
taskForm: FormGroup = this.formBuilder.group({
weekDays: this.formBuilder.array([
this.formBuilder.control(false),
this.formBuilder.control(false),
this.formBuilder.control(false),
this.formBuilder.control(false),
this.formBuilder.control(false),
this.formBuilder.control(false),
this.formBuilder.control(false),
]),
});
html:
<!-- weekdays -->
<div class="task-form-control" *ngIf="isRecurrent">
<mat-label>Tage</mat-label>
<div class="weekdays" formArrayName="weekDays">
<mat-checkbox
*ngFor="
let weekDay of taskForm.get('weekDays').value;
let i = index
"
color="primary"
labelPosition="before"
[formControlName]="i"
>{{ weekDaysDe[i] }}</mat-checkbox
>
</div>
</div>
The checkboxes are rendered as expected but there are two problems:
What have I done wrong?
Upvotes: 0
Views: 4447
Reputation: 27303
In template, Use Form Array controls to iterate over with *ngFor.
Try this:
<div class="weekdays" formArrayName="weekDays">
<mat-checkbox *ngFor="
let weekDay of weekDaysArray.controls;
let i = index
" color="primary" labelPosition="before" [formControlName]="i">{{ weekDaysDe[i] }}
</mat-checkbox>
</div>
Access the FormArray control with a getter method like this.
componen.ts
get weekDaysArray() : FormArray{
return this.taskForm.get('weekDays') as FormArray;
}
Upvotes: 2