AI Hints
Home›Angular Tutorial›host Listeners, Template Reference Variables and Practice: A Price List
Angular · Lesson 63 of 120

Practice: A Price List

Your turn.

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

Let's practise pipes. You'll write a discount pipe, and use it to build a sale price list.

  • A discount pipe
  • A sale price list
  • Your turn

A discount pipe

Your turn. Pause the video, and try this. Write a discount pipe, that takes a percentage as its argument. Then list the books, with the old price crossed out, and the sale price after it. Here is one solution. Transform takes the price, and the percent, with ten as the default. It returns the reduced price. Every book now shows its sale price.

✍️ Exercise: A discount pipe

Write a "discount" pipe: price | discount: 20 returns the price minus 20%. List each book with the old price in <s> and the sale price, both formatted with currency: 'GBP'.

Show hint

transform(price: number, percent = 10) { return price * (1 - percent / 100); }

Show solution
discount-pipe.tstypescript
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'discount' })
export class DiscountPipe implements PipeTransform {
  transform(price: number, percent = 10): number {
    return price * (1 - percent / 100);
  }
}

app.ts

The template chains two pipes. Discount takes twenty percent off, and currency formats the result. The old price is wrapped in an s tag, so it's crossed out.

app.tstypescript
import { Component } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { DiscountPipe } from './discount-pipe';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  imports: [CurrencyPipe, DiscountPipe],
  template: `
    <h2>Summer sale: 20% off</h2>
    @for (b of books; track b.id) {
      <p><s>{{ b.price | currency: 'GBP' }}</s>
        {{ b.title }}: <b>{{ b.price | discount: 20 | currency: 'GBP' }}</b></p>
    }
  `,
})
export class App {
  books = BOOKS;
}

What module seven taught

Pipes format values, with arguments, and chaining. Custom pipes have a transform method. Directives change elements, with host bindings, and host listeners. And a hash names an element in a template.

keyvalue
value | pipe: argformat values
@Pipe + transformyour own pipes
@Directive + hostchange elements
#refname an element

Summary

You can now format values, and add behaviour to elements. That's the end of module seven. Next, services, and dependency injection.

Key takeaways
  • Pipes
  • Directives
  • #ref
Next up: Why Services — share code and data