I have a fairly complex page with many nested components, some of which have forms with inputs on them (mostly reactive, though I'm sure there are some template driven forms somewhere). There's a 'Submit' button in the footer, that's only supposed to be enabled if all the inputs on all the forms are valid.
I've decided I'll create a "page validity service" that will hold a list of all the invalid forms and expose an 'is valid' observable for the button to consume. That means each component will have to call "add me to the invalid forms list" or "remove me from invalid forms list" whenever the validity of the form changes. To minimize the number of calls, I only want to make the call when the form status really changes (ie goes from valid to invalid or vice versa) I've tried subscribing to statusChanges:
this.formGroup.statusChanges.subscribe((status) => {}
but that one fires every time the value is updated (which I've set to onBlur) regardless of whether or not the status has changed. In fact it seems to fire exactly at the same time as onChanges. Is there a way to only get notified by the form when the validity actually changes, or do I have to do the check manually in each component? The project is in Angular 13.
CodePudding user response:
Yes, it is possible to omit superfluous events that you are not interested in by using the distinctUntilChanged
operator.
Give this a shot:
this.formGroup.statusChanges.pipe(distinctUntilChanged()).subscribe((status) => {
console.log(`the new status is ${status}`);
});