Create an Angular Signal Which Stores a Value

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet

This lesson teaches how to create a signal in Angular with the signal function from @angular/core. Signals need an initial value, which can be a primitive, object, or any other valid expression in JavaScript.

TypeScript infers the signal's type and catches errors during compilation.

[00:01] Create a property on the class and import the signal function from Angular core. Run the function and provide the initial value for the signal. Here we have created a string signal, and TypeScript correctly infers that the type of the writable signal is a string. We could create a [00:21] primitive signal but we could also create an object based signal or a nested object or any other valid expression in JavaScript. If you wanted to create a signal without providing the initial value you would get a typescript [00:41] compilation error saying that the initial value parameter is required but it was not provided. If you wanted to create a signal with the undefined initial value, TypeScript would infer the type of the signal as undefined only, which probably wouldn't be very useful. So if you wanted to create a signal [01:01] which would have a string value but only initially it would start with an undefined you would have to pass the type parameter explicitly saying that it could be either a string or undefined so the type parameter would have to be a TypeScript union.