假设我有一个表单来创建商店。我想输入它的名字,以及商店开放的日子。
所以我会有一个带有一些输入的表单,我想在一个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
});
}
它不起作用,我无法理解为什么......
编辑:感谢@ g-tranter(以及其他SO帖子),我可以解决这个问题。最终代码如下:
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
});
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
您正在将表单控件名称设置为数字索引:
formControlName="{{i}}"
在表单组中不存在。
您需要将其设置为&#34;星期一&#34;等或设置
[formControl]="availableDay"