Questions
What are pipes and how do you use them in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that needs to display a date in a user-friendly format.
You could format the date in the component’s class, but this would not be a very reusable solution.
The Challenge
Explain what pipes are in Angular and how you would use them to solve this problem. What are the key benefits of using pipes?
A junior engineer might try to solve this problem by formatting the date in the component's class. This would work, but it would not be a very reusable solution.
A senior engineer would know that a pipe is the perfect tool for this job. They would be able to explain what a pipe is and how to use it to format a date in a user-friendly way.
Step 1: Understand What Pipes Are
A pipe is a way to transform data in your template. It takes in data as input and returns a transformed version of that data.
Step 2: The Different Types of Pipes
| Type | Description |
|---|---|
| Pure | A pure pipe is only called when its input changes. This is the default. |
| Impure | An impure pipe is called on every change detection cycle. |
Step 3: Use a Built-in Pipe
Angular has a number of built-in pipes that you can use, such as:
DatePipeUpperCasePipeLowerCasePipeCurrencyPipeDecimalPipePercentPipe
Here’s how we can use the DatePipe to format a date:
{{ myDate | date:'medium' }}Step 4: Create a Custom Pipe
You can also create your own custom pipes. Here’s how we can create a custom pipe to truncate a string:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number): string {
return value.length < limit ? value : value.slice(0, limit) + '...';
}
}We can then use the custom pipe in our template:
{{ myString | truncate:10 }} Practice Question
You are building a component that displays a list of items that are being filtered in real-time. Which type of pipe would you use for the filter?