[Angular] pipe() 함수란?

Yuri Lee·2022년 4월 21일
0

Intro

데이터 표시 형식 중 단위 별로 다르게 표시를 했어어야 했다. 위 상황에서 pipe를 활용해 손쉽게 표시할 수 있다.

Pipe란?

Pipe 는 템플릿에서 값의 표시되는 형태를 변환해서 보여주기 위해서 사용한다. 하지만 데이터 값 자체를 변형시켜서 보여주기에는 side effect 가 발생할 수 있으므로 화면에 표시되는 형식만 변경하고 싶을 때 사용하는 것이 파이프이다.

사용법

<!-- 기본사용법 -->
{{ value | PipeName }}

<!-- 옵션지정 -->
{{ value | PipeName : Option : OptionValue }}

<!-- 체이닝 -->
{{ value | PipeName1 | PipeName2 }}

디버깅할 때 많이 쓰는 json 형식으로 변경시켜주는 파이프를 실행

{{ data | json }}

built-in pipes

  • DatePipe : Formats a date value according to locale rules.
  • UpperCasePipe : Transforms text to all upper case.
  • LowerCasePipe : Transforms text to all lower case.
  • CurrencyPipe : Transforms a number to a currency string, formatted according to locale rules.
  • DecimalPipe : Transforms a number into a string with a decimal point, formatted according to locale rules.
  • PercentPipe : Transforms a number to a percentage string, formatted according to locale rules.

custome pipes

custome pipes 를 직접 만들 수도 있다.

// mypipe.pipe.ts

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

@Pipe({
  name: 'mypipe',
})
export class Mypipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return null
  }
}

파이프의 이름은 mypipe 이며 PipeTransform 인터페이스의 추상메서드인 transform() 을 구현해야 한다. value 는 변환 대상인 값, args는 옵션이다.

// app.module.ts
// ...생략
@NgModule({
  declarations: [
    Mypipe, // 추가
  ],
  //...
})

이렇게 만들어 놓은 커스텀 파이프는 모듈의 declarations 에 등록해야 한다.

# 커스텀파이프 생성
$ ng generate pipe mypipe

# 축약형
$ ng g p mypipe

위의 작업은 angular-cli 를 통해 한번에 할 수 있다.

# 커스텀파이프 생성
$ ng generate pipe mypipe

# 축약형
$ ng g p mypipe

사용법도 빌트인과 동일하다.

{{ data | mypipe }}

https://www.heecheolman.dev/post/angular-%ED%8C%8C%EC%9D%B4%ED%94%84/
https://angular.io/guide/pipes
https://medium.com/witinweb/angular-4-2-pipes-%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C-651848186633

profile
Step by step goes a long way ✨

0개의 댓글