如何跟踪反应形式中未保存的更改?如何防止用户在保存前单击同一页面上的按钮?

How to track unsaved changes in reactive forms ? How to prevent user from clicking buttons on the same page before saving?

我已经使用反应式表单方法创建了一个表单,现在我想阻止用户在有未保存的更改时点击按钮。

我尝试使用 -

if (this.exampleForm.dirty) {
    alert('Unsaved Changes');
} else {
   --proceed logic
}

但是即使用户保存了未保存的更改,这也总是使表单变脏。

任何人都可以向我建议实现此目标的更好方法吗?

既然您已经说过您正在使用反应式表单方法,那么您可以简单地使用 dirty:

<div class="important" *ngIf="createPrpjectDetailsForm.dirty == true">Form changes need to be saved first before submitting order.</div>
<button type="button" *ngIf="createPrpjectDetailsForm.dirty == false">Submit</button>

并且如 L.Loscos 所述,在保存时将表单标记为原始状态。 this.createPrpjectDetailsForm.markAsPristine()