onChange hook

This hook might be used for many use cases. One of them to update the view after state was changed if you are not using:

  • actions

  • async pipes

for example:

Selected location: {{ location }}
location: any;

constructor(private store: Store<any>, private cd: ChangeDetectorRef) { }

ngOnInit() {
    this.filters = new FormGroup({
        condition: new FormGroup({
            new: new FormControl(false),
            used: new FormControl(false),
            notSpecified: new FormControl(false)
        }),
        location: new FormControl()
    });

    this.store.select(['form', 'location']).subscribe(state => this.location = state);

    this.ngFormStateManager = this.store.select(['form'])
        .form.bind(this.filters)
        .shouldUpdateState((params: ShoulUpdateStateParams) => true)
        .onChange(state => // Do something with changes);
}

This event will not be triggered if you are updating form state from the code manually

This becomes handy for example when you want to change one state property value depending on another change. For this you can do following:

const ngFormStateManager = this.actions.store.form
    .bind(this.form, { emitEvent: true, onChangePairwise: true })
    .onChange(([prev, curr]) => {
        if (prev.monthlyIncome !== curr.monthlyIncome) {
            this.recalculateQuarterIncome(curr.monthlyIncome!);
        }

        if (prev.quarterIncome !== curr.quarterIncome) {
            this.recalculateMonthlyIncome(curr.quarterIncome!);
        }
    });

Last updated

Was this helpful?