typescript 30 lines · 5 steps

Signal inputs and computed in Angular

A rating-stars component derives its rendered state from signal inputs using computed values that recalculate automatically.

Explained by highlit
1import { Component, input, computed } from '@angular/core';
2 
3function toNumber(value: number | string): number {
4 return typeof value === 'number' ? value : parseFloat(value);
5}
6 
7@Component({
8 selector: 'app-rating-stars',
9 standalone: true,
10 template: `
11 <div class="stars" [attr.aria-label]="label()">
12 @for (star of stars(); track $index) {
13 <span class="star" [class.filled]="star">★</span>
14 }
15 </div>
16 `,
17})
18export class RatingStarsComponent {
19 readonly value = input.required({ transform: toNumber });
20 readonly max = input(5, { transform: toNumber });
21 
22 protected readonly stars = computed(() => {
23 const filled = Math.round(this.value());
24 return Array.from({ length: this.max() }, (_, i) => i < filled);
25 });
26 
27 protected readonly label = computed(
28 () => `${this.value()} out of ${this.max()} stars`,
29 );
30}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Signal inputs with a transform coerce raw bindings into the type your component expects.
  2. 2computed signals derive state that stays in sync whenever their source signals change.
  3. 3Rendering from derived signals keeps templates declarative and free of manual update logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Signal inputs and computed in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code