我使用角度反应形式和 NgRx 商店。我想要实现的是存储表单脏/原始状态并对其在另一个组件中的更改做出反应。
我熟悉表单的
statusChanges
和 valueChanges
属性,它们返回适当信息的 Observable。您能帮助我以类似的方式获得肮脏/原始的状态吗?
是的,我找到了解决方案。 valueChanges 的观察者只能检查脏/原始状态。即:
this.myForm.valueChanges.subscribe(() => {
console.log(`Is form dirty?: ${this.myForm.dirty}`);
});
正如我们在 JavaScript 中一样,我们可以进行“险恶”的 hack,以类似事件的方式抓住
markAsPristine()
和 markAsDirty()
:拦截函数调用本身!
例如,如果您有一个名为
this.formGroup
的 Angular FormGroup,则不带括号“()”的 this.formGroup.markAsPristine
是函数本身,而不是对它的调用!
我们可以将此函数存储到常量中并使用新的实现进行重载
this.formGroup.markAsPristine
:
const oldFuncPristine = this.formGroup.markAsPristine;
const fg = this.formGroup;
this.formGroup.markAsPristine = function() {
oldFuncPristine.apply(fg);
console.log("formGroup marked PRISTINE");
// ...other code, e.g. sending events
};
好的,但是为什么我们需要常数
fg
?
好吧,我们用 function() {...}
定义一个纯函数。该函数在其范围内不会“看到” this 。因此,我们使用这种不太复杂的方式来让函数了解 FormGroup 和 this
。
有一种更好的方法可以将其传递给函数,但这不是本文的主题。如果好奇,请参阅 有关 bind()、apply()、call() 的博客
希望对您有帮助。
现在,Angular 18 FormControl 具有
events
Observable,您可以在其中监听 PristineChangeEvent
等事件
this.form.events.pipe(takeUntilDestroyed()).subscribe((event) => {
if (event instanceof PristineChangeEvent) {
console.log('form pristine change ', event.pristine);
console.log(this.form.pristine); // same same
}
});