この記事の概要
ネストしたフォームグループのバリデーションの設定はそのままに値を初期化したい時、フォームグループの項目が多い場合、一つ一つpatchValueしていくのは大変です。
そこで、ネストフォームグループの初期設定を外だしして、setControlを使って初期化します。
実装
parentForm: FormGroup;
get fCtrl(): { [key: string]: AbstractControl } {
return this.parentForm.controls;
}
get fChildCtrl(): { [key: string]: AbstractControl } {
return (this.parentForm.controls.childGroup as FormGroup).controls;
}
constructor(
private fb: FormBuilder
) { }
ngOnInit() {
this.parentForm = this.fb.group({
id: [null],
parentName: [null, [Validators.required]],
childGroup: this.getDefaultChildForm()
}, {
updateOn: 'submit'
});
}
/**
* 子フォームグループの初期値取得.
*/
private getDefaultChildForm(): FormGroup {
return this.fb.group({
childName: [null, [Validators.required]],
childCount: [null, [Validators.required]]
});
}
/**
* 子フォームグループを初期値する.
*/
onInitChildForm(): void {
this.parentForm.setControl('childGroup', this.getDefaultChildForm());
}
onSubmit(): void {
if (this.parentForm.invalid) {
alert('invalid!');
return;
}
// submit処理
}
<mat-card>
<form
[formGroup]="parentForm"
(ngSubmit)="onSubmit()">
<mat-card-content>
<mat-form-field class="form-element">
<mat-label>parentName</mat-label>
<input
matInput
formControlName="parentName">
<mat-error *ngIf="!fCtrl.parentName.valid">必須項目です</mat-error>
</mat-form-field>
<div formGroupName="childGroup">
<mat-form-field class="form-element">
<mat-label>childName</mat-label>
<input
matInput
formControlName="childName">
<mat-error *ngIf="!fChildCtrl.childName.valid">必須項目です</mat-error>
</mat-form-field>
<mat-form-field class="form-element">
<mat-label>childCount</mat-label>
<input
matInput
formControlName="childCount">
<mat-error *ngIf="!fChildCtrl.childCount.valid">必須項目です</mat-error>
</mat-form-field>
</div>
</mat-card-content>
<mat-card-actions>
<button
mat-raised-button
type="submit"
color="primary">
登録
</button>
<button
mat-raised-button
type="button"
(click)="onInitChildForm()"
color="primary">
子フォーム初期化
</button>
</mat-card-actions>
</form>
</mat-card>
動作確認
入力

初期化

登録ボタン押下
