Reputation: 1396
Let's say I have a form to create a store. I want to input its name, and the days the store will be open.
So I'll have a form, with some inputs, and I want to group checkboxes in one mat-form-field.
store-form-component.html :
<form (ngSubmit)="onSaveStore()" [formGroup]="storeForm">
<mat-form-field>
<mat-label>Store name</mat-label>
<input matInput placeholder="store name" formControlName="name" required>
</mat-form-field>
<mat-form-field [formGroup]="storeForm.controls.availableDays>
<mat-checkbox *ngFor="let availableDay of storeForm.controls.availableDays.controls; let i=index" formControlName="{{i}}">{{i}}</mat-checkbox>
</mat-form-field >
</form>
store-form-component.ts :
export class StoreFormComponent implements OnInit {
// Form Groups
storeForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) {}
ngOnInit(): void {
this.initForm();
}
initForm(): void {
this.storeForm = this.formBuilder.group({
name: "",
availableDays: this.getAvailableDays()
});
}
getAvailableDays(): FormGroup {
return this.formBuilder.group({
monday: false,
tuesday: false,
wednesday: false,
thursday: false,
friday: false,
saturday: false,
sunday: false
});
}
It does not work and I can't figure why...
edit : thanks to @g-tranter (and others SO posts), I could fix the issue. The final code looks like :
store-form-component.html :
<form (ngSubmit)="onSaveStore()" [formGroup]="storeForm">
<div [formGroup]="storeForm.controls.availableDays">
<mat-checkbox *ngFor="let availableDay of days;" formControlName="{{availableDay}}">{{availableDay}}</mat-checkbox>
</div>
</form>
store-form-component.ts :
export class StoreComponent implements OnInit {
// Form Groups
storeForm: FormGroup;
days: Array<string>;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.initForm();
// this is useful to iterate over the form group
this.days = Object.keys(this.storeForm.controls.availableDays.value);
}
initForm(): void {
this.storeForm = this.formBuilder.group({
name: "",
availableDays: this.getAvailableDays()
});
}
getAvailableDays(): FormGroup {
return this.formBuilder.group({
monday: false,
tuesday: false,
wednesday: false,
thursday: false,
friday: false,
saturday: false,
sunday: false
});
}
}
Upvotes: 12
Views: 31923
Reputation: 17908
You are setting the form control name to a numeric index:
formControlName="{{i}}"
which doesn't exist in the form group.
You need to set it to "monday" etc. or set
[formControl]="availableDay"
Upvotes: 2
Reputation: 126
Maybe you need a mat-selection-list
Check Angular Material documentation
Hope it helps you!
Upvotes: 9