AI Hints
Home›Angular Tutorial›Content Projection, Building a Small Component Tree and Practice: A Star Rating
Angular · Lesson 54 of 120

Practice: A Star Rating

Your turn.

⏱ 2 min read▶ Video at 1:03:45🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise component communication. You'll build a star rating, that works with two-way binding.

  • A star rating
  • Two-way binding
  • Your turn

A star rating

Your turn. Pause the video, and try this. Build a star rating component, with five stars. Clicking a star sets the rating. Use model, so the parent can bind its own signal, with banana in a box. Here is one solution. At for draws five stars, filled up to the rating. Clicking one sets the model. And the parent's signal follows. After clicking the fourth star, the parent shows four out of five.

✍️ Exercise: A star rating

Make StarRating with rating = model(0) and 5 clickable stars (★ up to the rating, ☆ after). The parent binds [(rating)] and shows "You rated it N out of 5".

Show hint

@for (n of [1, 2, 3, 4, 5]; track n) and (click)="rating.set(n)"

Show solution
star-rating.tstypescript
import { Component, model } from '@angular/core';

@Component({
  selector: 'app-star-rating',
  template: `
    @for (n of [1, 2, 3, 4, 5]; track n) {
      <span class="star" (click)="rating.set(n)">{{ n <= rating() ? '★' : '☆' }}</span>
    }
  `,
  styles: `.star { font-size: 44px; color: #dd0031; cursor: pointer; }`,
})
export class StarRating {
  rating = model(0);
}

What module six taught

Inputs pass data down, and required inputs must be given. Outputs send events up, with emit. Model does both ways, with banana in a box. And ng content passes HTML into a child.

keyvalue
input()data down
output()events up
model()both ways
<ng-content />pass HTML in

Summary

Your components can now work together, as a tree. That's the end of module six. Next, pipes, and directives.

Key takeaways
  • Data down
  • Events up
  • Projection
Next up: Pipes — format values