Create an Angular Signal Which Stores a Value

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet
Published 6 months ago
Updated 2 weeks ago

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.

egghead
egghead
~ 33 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today