形式的Angular 5状态不匹配控制状态



我正在使用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.get('priceEachControl').valueChanges.forEach(() => this.changeItem());

这是PriceEachControl值更改时称为的功能:

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

更新功能似乎可以正常工作,因为它不会在每次击键上调用changeItem(),但仅在我离开字段时。

问题是状态并不总是正确的。例如,假设在加载表单时,价格= 9.7。那是无效的值。(根据以下等级,如果存在小数点,则必须在小数点之后有2到4个数字。)如果我将其更改为9.75(有效值),在控制台输出中,我会看到

VALID
INVALID

,该服务未调用。但是,如果我将其更改回9.7(无效),则输出

INVALID
VALID

并调用服务。

我知道这不是我的正则是问题,因为显然控件本身的状态是正确的。此外,如果我将多个值放在有效的情况下,则表单状态如预期的有效。该问题仅在从有效状态切换到无效状态时发生,反之亦然。

如何确保表单状态使用仅输入的值,以使表单状态与控制状态匹配?控件更改后何时更新表单状态?

此行只查看当前状态
if(this.proposalitemform.status =="有效")

您应该挂在现状变化

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

最新更新