私は、アプリケーションでフォームを表示するために、angular5 reactivemodule を使用しています。また、必須のバリデータも使用しました。これにより、フィールドが赤色になり、ユーザーにエラー メッセージが表示されます。
期待通りに動作していますが、フォームをリセットすると
this.form.reset()
フォームには、特定のフィールドが必須であるという検証エラーが表示されます。また、form.markAsPristine() または form.markAsUntouched() を使用してこれを機能させましたが、可能なペアの複数の組み合わせを適用した後も問題は解決しません。
例.html
<form [formGroup]="checkForm" (ngSubmit)="submitForm()">
<mat-form-field>
<input matInput formControlName="name" placeholder="name" />
<mat-error *ngIf="checkForm.get('name').errors?.required">
Name is required.
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="email" placeholder="email" />
<mat-error *ngIf="checkForm.get('email').errors?.required">
Name is required.
</mat-error>
</mat-form-field>
<button [disabled]="checkForm.invalid" type="submit">add</button>
</form>
例.ts
checkForm = this.formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.required]
});
submitForm() {
this.checkForm.reset();
// this.checkForm.markAsPristine();
this.checkForm.markAsUntouched();
}
どのような助けでも大歓迎です。
ベストアンサー1
デフォルトでは、Angular/Material
formControlのエラー状態を監視するだけでなくtouched
、提出済みフォームのステータスについては下記を参照してくださいソースコード。
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.touched || (form && form.submitted)));
^^^^^^^^^^^^^^
}
上記の理由により、フォームをunsubmitted
ステータスにリセットする必要もあります。
電話をかけることができますフォームをリセットのFormGroupDirective
(インスタンスを取得するViewChild
) をクリックすると、フォーム データと送信ステータスの両方がリセットされます。
<form #form="ngForm" [formGroup]="checkForm" (ngSubmit)="submitForm(form)">
...
</form>
@ViewChild('form') form;
submitForm() {
this.form.resetForm();
...
}
フォームの送信ステータスを無視するなどのカスタム条件を使用して ErrorStateMatcher を実装し、それをマテリアル コンポーネントに適用することで、デフォルトのものを上書きすることもできます。
<mat-form-field>
<input matInput formControlName="name" placeholder="name" [errorStateMatcher]="errorMatcher" />
<mat-error *ngIf="checkForm.get('name').errors?.required">
Name is required.
</mat-error>
</mat-form-field>
// define custom ErrorStateMatcher
export class CustomErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl, form: NgForm | FormGroupDirective | null) {
return control && control.invalid && control.touched;
}
}
// component code
@Component({...})
export class CustomComponent {
// create instance of custom ErrorStateMatcher
errorMatcher = new CustomErrorStateMatcher();
}
固定を参照デモ。