본문 바로가기

개발 공부/Angular

Angular의 내장 파이프(Built-in Pipes) (2) - Custom

Angular에서는 @Pipe 데코레이터로 자신만의 파이프를 만들 수도 있습니다.

 

사용 예시 -  포스트 등록 시간 커스텀

 

범위 출력 형태
1분~59분 n분 전
1시간~23시간 59분 n시간 전
1일~7일 n일 전
8일~4주 n주 전
1달~12달 n달 전
1년 이상 YY.MM.DD

 

 

1. 커스텀 파이프 

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'timeAgo'
})
export class TimeAgoPipe implements PipeTransform {
  transform(value: Date | string | number): string {
    const now = new Date();
    const date = new Date(value);
    const diffMs = now.getTime() - date.getTime();

    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);
    const diffWeeks = Math.floor(diffDays / 7);
    const diffMonths = Math.floor(diffDays / 30); // rough
    const diffYears = Math.floor(diffDays / 365);

    if (diffMins < 1) return '방금 전';
    if (diffMins < 60) return `${diffMins}분 전`;
    if (diffHours < 24) return `${diffHours}시간 전`;
    if (diffDays < 8) return `${diffDays}일 전`;
    if (diffDays < 29) return `${diffWeeks}주 전`;
    if (diffDays < 365) return `${diffMonths}달 전`;

    // 1년 이상이면 날짜 표기 (YY.MM.DD)
    const yy = String(date.getFullYear()).slice(2);
    const mm = String(date.getMonth() + 1).padStart(2, '0');
    const dd = String(date.getDate()).padStart(2, '0');
    return `${yy}.${mm}.${dd}`;
  }
}

 

 

2. 템플릿에서 사용 예시

<span>{{ someDate | timeAgo }}</span>
<!-- 출력 예시: 5분 전, 3일 전, 2주 전, 8달 전, 23.04.10 -->

 

 

3. NgModule에 등록

@NgModule({
  declarations: [TimeAgoPipe],
  exports: [TimeAgoPipe]
})
export class SharedModule {}

 

 


이처럼 커스텀 파이프를 생성하여 사용하면 재사용성이 우수하며, 특히 함수형으로 계속 호출하는것 보다 html에서 직접 접근이 가능하여 작업 속도 또한 우수합니다.

또한, 로직이 파이프 안에 따로 있기 때문에, 나중에 포맷 수정이 필요해도 템플릿을 손대지 않아도 됩니다.