포스트

[Angular 마스터하기] Day 13 - 파이프, 데이터 변환의 마법

[Angular 마스터하기] Day 13 - 파이프, 데이터 변환의 마법

이제와서 시작하는 Angular 마스터하기 - Day 13 “파이프로 데이터를 원하는 형태로 변환하세요! 🔧”

오늘 배울 내용

  • 내장 파이프 사용법
  • 커스텀 파이프 만들기
  • 파이프 체이닝
  • Pure vs Impure 파이프

1. 내장 파이프

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Component({
  selector: 'app-built-in-pipes',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="pipes-demo">
      <!-- DatePipe -->
      <p>날짜: {{ today | date:'yyyy-MM-dd' }}</p>
      <p>시간: {{ today | date:'HH:mm:ss' }}</p>

      <!-- CurrencyPipe -->
      <p>가격: {{ price | currency:'KRW':'symbol':'1.0-0' }}</p>

      <!-- PercentPipe -->
      <p>할인율: {{ discount | percent:'1.0-2' }}</p>

      <!-- UpperCasePipe, LowerCasePipe -->
      <p>대문자: {{ message | uppercase }}</p>
      <p>소문자: {{ message | lowercase }}</p>

      <!-- JsonPipe -->
      <pre>{{ user | json }}</pre>
    </div>
  `
})

export class BuiltInPipesComponent {
  today = new Date();
  price = 123456;
  discount = 0.15;
  message = 'Hello Angular';
  user = { name: '홍길동', age: 25 };
}

2. 커스텀 파이프

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate',
  standalone: true
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit: number = 20, ellipsis: string = '...'): string {
    if (!value) return '';
    if (value.length <= limit) return value;
    return value.substring(0, limit) + ellipsis;
  }
}

// 사용

@Component({
  imports: [TruncatePipe],
  template: `
    <p>{{ longText | truncate:50 }}</p>
  `
})

export class AppComponent {
  longText = '매우 긴 텍스트...';
}

실용적인 커스텀 파이프

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 상대 시간 파이프
@Pipe({
  name: 'timeAgo',
  standalone: true
})
export class TimeAgoPipe implements PipeTransform {
  transform(value: Date): string {
    const now = new Date();
    const seconds = Math.floor((now.getTime() - value.getTime()) / 1000);

    if (seconds < 60) return `${seconds}초 전`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}분 전`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}시간 전`;
    return `${Math.floor(seconds / 86400)}일 전`;
  }
}

// 파일 크기 파이프
@Pipe({
  name: 'fileSize',
  standalone: true
})
export class FileSizePipe implements PipeTransform {
  transform(bytes: number): string {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  }
}

3. 파이프 체이닝

1
2
3
4
5
6
7
8
@Component({
  template: `
    <!-- 여러 파이프 연결 -->
    <p>{{ message | uppercase | truncate:10 }}</p>
    <p>{{ price | currency:'KRW' | uppercase }}</p>
    <p>{{ date | date:'short' | uppercase }}</p>
  `
})

📝 정리

주요 내장 파이프

파이프 용도 예시
date 날짜 형식 ``
currency 통화 형식 ``
percent 퍼센트 ``
json JSON 출력 ``

체크리스트

  • 내장 파이프를 사용할 수 있나요?
  • 커스텀 파이프를 만들 수 있나요?
  • 파이프를 체이닝할 수 있나요?

📚 다음 학습


“파이프로 데이터를 멋지게 변환하세요!” 🔧

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.