Access an Angular Signal's Value and Display It Within the Component Template

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet
Published 6 months ago
Updated a week ago

Signals are functions that return their current value. The component template is guaranteed to be updated when the signal value changes.

TypeScript helps catch errors when using signals of different types. Signals can also be used with Angular's ngFor directive to loop over arrays.

[00:00] Call the signal as a function. Technically, an Angular signal is a function that returns the current signal value whenever it's called. Now when the signal value changes, Angular components template is guaranteed to get updated. Now if we change the default value of the signal to hey, we can see that it gets displayed [00:20] in the Angular template. Thanks to TypeScript, Angular is capable of narrowing down the type of the signal. Our item signal has value of type either string or undefined. And if we try to treat it as if it was a string, we can get a TypeScript error saying that object is possibly undefined because [00:40] the union is including the 2 types, either string or undefined. And TypeScript doesn't know in compile time which of them is going to be so we can put the optional chaining over here. We can also use signals within the angular for loop. For this reason, we'll create a new signal which [01:00] value is going to be an array and we'll call it items. So items equals a new signal which value is an array. And here I'll just quickly paste the 3 items, Andy, Bob, and Charlie. And we're going to iterate over the items. We need to define what is the track we're going to track by [01:20] ID. Now we're going to display it as a unordered list. Let's close the ul tag. And now for each element of the list, we're going to display the li and let's just display what the name of the item is here within the list. [01:40] And let's just save and display we've got Andy, Bob and Charlie.

egghead
egghead
~ 15 minutes 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