gpt4 book ai didi

Angular Material : Reseting reactiveform shows validation error

转载 作者:太空狗 更新时间:2023-10-29 17:41:29 24 4
gpt4 key购买 nike

我正在使用 angular5 reactivemodule 在我的应用程序中显示一个表单。我还使用了必需的验证器,它随后会将字段设置为红色并向用户显示错误消息。

它按预期工作,但是当我使用

重置表单时

this.form.reset()

表单向我显示了一个验证错误,指出特定字段是必需的。我还使用 form.markAsPristine() 或 form.markAsUntouched() 使其工作,但在应用可能对的多个组合后问题仍然存在。

example.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>

example.ts

checkForm  = this.formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.required]
});

submitForm() {
this.checkForm.reset();
// this.checkForm.markAsPristine();
this.checkForm.markAsUntouched();
}

感谢任何帮助。

最佳答案

默认Angular/Material不仅通过touched而且通过submitted状态观察formControl的错误状态表格,见下文source code .

isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.touched || (form && form.submitted)));
^^^^^^^^^^^^^^
}

由于上述原因,您还需要将表单重置为unsubmitted 状态。


您可以调用resetForm FormGroupDirective(通过 ViewChild 获取实例)因为它将重置表单数据和提交状态。

<form #form="ngForm" [formGroup]="checkForm" (ngSubmit)="submitForm(form)">
...
</form>

@ViewChild('form') form;

submitForm() {
this.form.resetForm();
...
}

您还可以通过使用自定义条件(例如忽略表单的提交状态)实现 ErrorStateMatcher 来覆盖默认值,并将其应用于 Material 组件。

<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();
}

参见固定 demo .

关于 Angular Material : Reseting reactiveform shows validation error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com