FormBuilder 控件导致“检查后表达式已更改"例外 [英] FormBuilder Control causing "Expression has changed after it was checked" exception
问题描述
我有一个通过 DynamicComponentLoader::loadIntoLocation
以编程方式实例化的表单.表单代码如下:
I have a form that is being instantiated programatically via DynamicComponentLoader::loadIntoLocation
. The form code is below:
constructor (
private _builder: FormBuilder
) {
this.editForm = _builder.group({
name: ['', Validators.required],
email: ['', Validators.compose([Validators.required, Helpers.emailValidator])],
phone: [''],
phoneAlt: [''],
location: [''],
dob: [''],
bio: [''],
});
}
您会注意到某些表单没有验证器(据我所知,这与使用 Validators.nullValidator
相同,我已经对两者进行了测试).
You'll notice that some of the forms don't have validators (as far as I can tell, this is the same as using Validators.nullValidator
, I've tested with both).
在我的模板中,我有以下代码(对于每个控件):
In my template I have the following code (for each control):
<label for="phone">Contact Number <span *ngIf="!phone.valid">- {{e(phone)}}</span></label>
<input type="text" name="phone" id="phone" ngControl="phone" #phone="ngForm">
第一个没有验证器的控件在遇到模板的 !phone.valid
部分时会抛出以下异常两次:
The first control that doesn't have a validator throws the following exception twice when it hits the !phone.valid
part of the template:
EXCEPTION: Expression '!phone.valid in e@15:43' has changed after it was checked. Previous value: 'true'. Current value: 'false' in [!phone.valid in e@15:43]
在初始创建之后,我从未接触过控件或 this.editForm
,因此,就我的代码而言,应该没有任何变化.
At no point am I touching the controls or this.editForm
after the initial creation, so, as far as my code is concerned, nothing should be changing.
我知道我可以通过调用 enableProdMode()
来抑制错误,但我宁愿解决问题而不是隐藏它.
I'm aware that I can suppress the errors by calling enableProdMode()
but I'd rather fix the problem than hide it.
编辑(2 月 8 日):此后我尝试将模态的内容移动到单独的页面,但错误仍然存在.这表明问题与我创建和加载模态的方式无关,而是与 ControlGroup 或 FormBuilder 相关.
Edit (8th Feb): I have since tried moving the contents of the modal to a separate page, but the errors persist. This would suggest the issue is not related to the way I am creating and loading the modals, but rather the ControlGroup or FormBuilder.
推荐答案
感谢 qdouble 在 Angular Gitter 聊天.
这个问题似乎是由 angular 解析页面的顺序引起的.从上到下,ngIf="!phone.valid"
在 phone.valid
被初始化之前被解析.通过在 if 语句中添加一个 catch 以确保它不是 null *ngIf="phone.valid === null ? false : !phone.valid"
(或通过移动输入后的标签).
The issue seemed to be caused by the order in which angular parsed the page. By going from top to bottom, ngIf="!phone.valid"
was being parsed before phone.valid
had been initialised. This was easily fixed by adding a catch in the if statement to make sure that it was not null *ngIf="phone.valid === null ? false : !phone.valid"
(or by moving the label after the input).
这篇关于FormBuilder 控件导致“检查后表达式已更改"例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!