Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular16 how to create a Signal without initial value

I updated my Angular app to v16 and I'm trying to use Signals. Before, I was initializing my variables without initial value

filters: Filter[];

but as I'm using Signals it gives me an error. An argument for 'initialValue' was not provided Is there a way I can create a Signal without initializing its value?

I tried setting its Type to possibly null and giving it null value

signal<Category | null>(null);

But some other errors occurred in the file like Object is possibly 'null'.

And I'm not a fan of using "any" type

So please can you provide another solution?

like image 544
farouk alahdab Avatar asked Jan 02 '26 00:01

farouk alahdab


2 Answers

The signals have been designed with to specifically always have a synchronous value.

This means you have to explicitly create a signal with null or undefined.

For example:

const mySignal = new Signal<{value:number}|null>(null). 

At the moment narrowing isn't working with signals in template. Expect an error when you do {{ mySignal().value }}.

You're going to have to rely on optional chaining operator (.?) : {{ mySignal()?.value }} to prevent that error.

The Angular team is aware of this issue and we can expect some improvements on that !

like image 66
Matthieu Riegler Avatar answered Jan 06 '26 10:01

Matthieu Riegler


How about defining it as a Partial?

signal<Partial<Category >>({});
like image 43
Akhil Padmanabhan Nair Avatar answered Jan 06 '26 09:01

Akhil Padmanabhan Nair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!