We have an Angular Child Form emitting values with Valuechanges. In the Parent Component we want to run tasks if the new zip code value from child is different from previous zip code value.
Right now, we are creating a variable to store previous zip codes.
Is there a cleaner way to conduct this with Output? I know NgOnchanges for Input, we can track previous changes with changes.previousValue.
Curious if Output value changes have something similar?
Child Form:
public addressSub = new Subscription();
public editAddressForm: FormGroup;
@Output addressFormChange = new EventEmitter<any>();
this.addressSub.add(this.editAddressForm.valueChanges.subscribe(data=> {
this.addressFormChange.emit(this.editAddressForm);
})))
Parent Component:
In the Parent, it is subscribing as.
public addressFormChangeEvent(addressFormEvent){
this.addressMailingForm = addressFormEvent;
if (this.addressMailingForm.get('zipCode') != previousZipCode) {
doSomethingetc();
}
previousZipCode = this.addressMailingForm.get('zipCode');
}
Does Angular have something in library to see previous values with ValueChanges Subscription?
IMO much simpler way of doing this is with help of pairwise and startWith.
Also, you could pass down the form from parent component to the child and subscribe in the parent component, eg:
form.valueChanges
.pipe(startWith(undefined), pairwise())
.subscribe(valuesArray => {
const newVal = valuesArray[1];
const oldVal = valuesArray[0];
if (newVal !== oldVal) {
// do your thing
}
})