![](/img/trans.png)
[英]Angular 5 reactive form- updating formControl through the html does not update the value, only the control
[英]angular 5, reactive form- resetting a required form control does not reset the required error under the input
在模板中,我有一个通过按下按钮打开的表单 -
<form [formGroup]="person"
(ngSubmit)="onSubmitNewPerson()"
#formDirective="ngForm">
<mat-form-field>
<input matInput formControlName="firstName" required>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="lastName" #last required>
</mat-form-field>
</form>
在组件中,我有这个代码-
@ViewChild('formDirective') formDirective: FormGroupDirective;
this.person = this.formBuilder.group({
lastName: ['', Validators.required],
firstName: ['', Validators.required]
});
关闭按钮后,我运行此功能-
this.formDirective.resetForm();//hack that I saw in some question
this.person.reset();
但是再次打开表单后,我立即看到输入下的红色错误。
我也试过这个-
this.person.get('firstName').markAsUntouched();
this.person.get('lastName').markAsUntouched();
this.person.get('firstName').markAsPristine();
this.person.get('lastName').markAsPristine();
但这也不起作用。
知道如何修复它吗?
当我想重置验证器时,我使用了以下一次:
this.person.get('firstName').clearValidators();
this.person.get('firstName').updateValueAndValidity();
只需从您的 html 模板中删除 required ,如果您想在焦点上显示错误消息,而不是尝试显示不同的错误消息。
这是 html 模板:
<div class="form-group">
<label for="name" class="form-control-label">
*Amount:
</label>
<input type="number" name="amount" class="form-control" [formControl]="form.controls['amount']">
<div>
<small *ngIf="form.controls['amount'].hasError('required') && form.controls['amount'].touched" class="text-danger">
Please enter an amount.
</small>
<small *ngIf="form.controls['amount'].hasError('min') && form.controls['amount'].touched" class="text-danger">
Your amount must be at least 0.01.
</small>
<small *ngIf="form.controls['amount'].hasError('max') && form.controls['amount'].touched" class="text-danger">
Your amount cannot exceed 999999.99.
</small>
</div>
这是 component.ts
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
constructor(private fb: FormBuilder) { }
this.form = this.fb.group({
amount: [null, Validators.compose([Validators.required, Validators.min(0.01), Validators.max(999999.99)])],
});
虽然这个问题有点老,但这个答案可能会帮助有这个问题的人。
如果这个问题出现在 Angular material mat-stepper
,您可以查看针对此问题提供的解决方案。
(这就是为什么一些受访者无法重现问题的原因)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.