angularangular-servicesangular-signals

How to identify the correct Angular signal with effect()?


The signals in Angular are pretty nice. However I'm struggling with handle multiple signals. In a very simplified example is a service ExternalController that defines two signals controller1 and controller2.

Now I want to trigger a method if a signal value changes.

service ExternalController {
    public controller1 = signal(null);
    public controller2 = signal(null);

    constructor() {
        effect(() => {
            if (controller1) do something
            if (controller2) do something else
        })
    }
}

The problem is that effect() fires whenever a signal has changed. But how can I find out which signal has fired?


Solution

  • Effect callbacks are run in a reactive context. It means it's able to know on which signal it depens. If you only call a single signal in effect, this effect will only be invoked when the said signal is updated.

    Effect does not run for signal updates that are invoked outside of it.

    In you case you could have 2 effects :

    effect(() => {
       if (controller1()) {
         ...
       }
    })
    
    effect(() => {
       if (controller2()) {
         ...
       }
    })