2

I am writing code using Angular 16 Signals. The code will compute a signal that also use Input value. Some of my component works fine but there is a single component that when I inspect, the Input value is still undefined which means that the computation of the signal is done before OnInit. The other component that works fine perform OnInit before computing the value. I am just wondering, what is the actual timing for the signal computation to occur? Is there any documentation about this?

2
  • The computed() is recalculated the next time the signal is read. From the RFC: `Computations are lazy: the computation function is not invoked, unless someone is interested in (reads) its value.' See this link for more information: github.com/angular/angular/discussions/49683 under the topic "Computed Signals"
    – DeborahK
    Commented Jun 8, 2023 at 5:21
  • Hi, I have found the cause. I have an effect that use the signal. It seems the effect is triggered during the construct method and the invocation of the effect made the signal is being recalculated. That is why the signal get undefine value from the input variable. I was a bit confuse with the behavior because the effect is the one triggering the signal computation instead of reverse.
    – Bharata
    Commented Jun 8, 2023 at 10:59

1 Answer 1

2

Important thing to remember here is that the effect always runs one time. So that’s why the effect can be the first time the signal is accessed. That's very different from say the subscribe method for RxJS. I think it will be very common for hastily converted code to have unexpected side effects due to this difference.

There’s also no guarantee exactly when the effect will run (and that may change in future and probably will for signal components), but for sure it can’t run if you haven’t created it yet…

Therefore you can just as well create an effect in the constructor, ngOnInit, ngAfterViewInit etc. It just needs to be in an injector context or otherwise you need to provide injector via the options parameter.

2
  • 1
    For me, the workaround is to add another boolean signal as the dependency for the effect. During ngAfterViewInit, I set the boolean to true, means the effect will be run at that time and not during constructor. That way the input is already available.
    – Bharata
    Commented Jul 24, 2023 at 5:45
  • 2
    For now we can use input function that will return InputSignal instead of @Input decorator. See angular.dev/guide/components/inputs Commented Dec 12, 2024 at 8:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.