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?
1 Answer
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.
-
1For 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.– BharataCommented Jul 24, 2023 at 5:45
-
2For now we can use
input
function that will returnInputSignal
instead of@Input
decorator. See angular.dev/guide/components/inputs Commented Dec 12, 2024 at 8:33
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"