Angular 窗体的状态与控件的状态不匹配
我使用的是Angular 5.1.0。我使用的是反应形式 设置表单时,我使用:Angular 窗体的状态与控件的状态不匹配,angular,forms,validation,Angular,Forms,Validation,我使用的是Angular 5.1.0。我使用的是反应形式 设置表单时,我使用: this.proposalItemForm = this.fb.group({ ... priceEachControl: [this.proposalItem.priceEach, { updateOn: 'blur', validators: [Validators.required, Validators.pattern("^[0-9]*(?:[.][0-9]{2,4})?$")] }],
this.proposalItemForm = this.fb.group({
...
priceEachControl: [this.proposalItem.priceEach, { updateOn: 'blur', validators: [Validators.required, Validators.pattern("^[0-9]*(?:[.][0-9]{2,4})?$")] }],
...
});
我还使用以下方法设置了数据更改侦听器:
this.proposalItemForm.get('priceEachControl').valueChanges.forEach(() => this.changeItem());
以下是当PriceAchControl值更改时调用的函数:
changeItem() {
console.log(this.proposalItemForm.get("priceEachControl").status);
// make sure the entire form is valid
console.log(this.proposalItemForm.status);
if (this.proposalItemForm.status=="VALID") {
// first, make sure the data model matches the form model
this.proposalItem = this.prepareSaveItem();
// then submit the updated data model to the server
this.proposalItemService.update(this.proposalItem).subscribe(
data => {
this.proposalItem = data;
},
error => {
if (error.exception=="EntityNotFoundException") {
this.messagesService.error(error.message);
}
else {
this.messagesService.error("There was a problem updating the proposal item.");
console.error("Error: ", error);
}
},
() => {}
);
}
}
updateOn功能似乎工作正常,因为它不会在每次击键时调用changeItem()
,而是在我离开字段时才调用
问题是状态并不总是正确的。例如,假设加载表单时priceEach=9.7。这是一个无效的值。(根据正则表达式,如果存在小数点,则小数点后必须有2到4个数字。)如果我将其更改为9.75(有效值),我将在控制台输出中看到
VALID
INVALID
并且服务没有被调用。但是,如果我将其更改回9.7(无效),那么它将输出
INVALID
VALID
并呼叫服务
我知道我的正则表达式没有问题,因为很明显控件本身的状态是正确的。此外,如果我在其中输入了多个有效值,那么表单状态将如预期的那样有效。该问题仅在从有效状态切换到无效状态或从无效状态切换到有效状态时发生
如何确保表单状态使用刚刚输入的值,以便表单状态与控件状态匹配?控件更改后表单状态何时更新?此行只查看当前状态
if(this.proposalItemForm.status==“VALID”) 您应该关注可观察到的状态变化
this.proposalItemForm.statusChanges.subscribe(status => {
if (status=="VALID")
//logic here
});
就这样
this.proposalItemForm.statusChanges.subscribe(status => {
if (status == "VALID") {
// first, make sure the data model matches the form model
this.proposalItem = this.prepareSaveItem();
// then submit the updated data model to the server
this.proposalItemService.update(this.proposalItem).subscribe(
data => {
this.proposalItem = data;
},
error => {
if (error.exception == "EntityNotFoundException") {
this.messagesService.error(error.message);
} else {
this.messagesService.error(
"There was a problem updating the proposal item."
);
console.error("Error: ", error);
}
},
() => {}
);
}
});
流程为:控制更新->触发控制的事件->父组更新->触发父组的事件。如果您订阅这样的控制事件,它将始终落后。