Search code examples
angular16angular-signals

Angular 16 signals side effects


Before signals, I had an observable that I would watch to trigger a FormControl's editable property, like this:

this.#isItEditor$
    .pipe(takeUntilDestroyed(this.#destroyRef))
    .subscribe(x => {
        const funded = this.formGroup.controls.funded
        if (x)
            funded.enable()
        else
            funded.disable()
    })

Now I've changed from an observable to a signal, but it feels like, in this case, I still need to create an observable from the signal to then do the pipe/subscribe the same way I used to.

I'm not assigning anything based on the signal changing, I'm just implementing a side effect. Is this correct?


Solution

  • You could use effect to listen signal changes. Effect will track signal reads and whenever value changes effect runs again.

    effect(() => {
      this.#isItEditor(); //Read signal here
      //Rest of the logic
        const funded = this.formGroup.controls.funded
        if (x)
            funded.enable()
        else
            funded.disable()
      
    });