Angular reset form when signal is true using effect()

338 views Asked by At

I'm wondering if I'm using signals correctly in the following use case. I have a form, which needs to be reset when the success signal is true. I've done so using an effect. However the Angular docs are not entirely clear about this yet (see here).

**Would you consider this a valid use of an effect? **

protected success = this.store.selectSignal(fakeFeatureName.selectSuccess);

constructor() {
    effect(() => {
      if (this.success()) {
        this.form.reset();
      }
    });
  }

Angular docs currently lists this a valid options to use an effect:

Effects are rarely needed in most application code, but may be useful in specific circumstances. Here are some examples of situations where an effect might be a good solution:

  • Logging data being displayed and when it changes, either for analytics or as a debugging tool
  • Keeping data in sync with window.localStorage
  • Adding custom DOM behavior that can't be expressed with template syntax
  • Performing custom rendering to a , charting library, or other third party UI library

BUT Avoid using effects for propagation of state changes

1

There are 1 answers

0
OZ_ On

If in the variable's description, you use words related to time, then you need an observable, not a signal. Signals have no "time" dimension. I'll quote my tweet here:

If the role of a variable can be described as conditions, then you need Angular Signals:

  • "if this variable has this value, then display this list"
  • "if this variable has this value, this button is disabled"

As you can see, Signals are great for the template control flow.

If the description of a variable's role includes words, related to time, you need Observables:

  • "when the cursor moves..."
  • "wait for the file uploading event and then..."
  • "every time this event happens, do this..."
  • "until this event..."
  • "for N seconds ignore..."

Signals are great for application state management, and I recommend you use signals in the templates of your components.

But you can see that Observables are still quite useful and helpful in Angular - unlike Signals, they have a "time" dimension and "completeness".