Angular Pipe
Pipe
내가 생각하는 pipe란?
- 전달받은 값을 변화시키는 것이다.
- angular에 date를 forrmat해주는 기능이 있는데 이게 미국식으로 변환시켜주기 때문에 원하는 결과를 얻지 못해 직접 구현했다.
-> 알고보니 angular 내장 파이프에 date forrmat 기능이 있었다. 하하
- angular에 date를 forrmat해주는 기능이 있는데 이게 미국식으로 변환시켜주기 때문에 원하는 결과를 얻지 못해 직접 구현했다.
생성
- xxx.pipe.ts 파일 생성
연결
- xxx.module.ts에 import{~} from ‘~’; / declarations: []에 추가
적용
- 내장파이프 말고 직접 코딩(datetimeFormat.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'datetimeFormat'})
export class datetimeFormatPipe implements PipeTransform {
transform(value: number): string {
let unix_timestamp = value;
let date = new Date(unix_timestamp * 1000);
let hours = date.getHours();
let minutes = "0" + date.getMinutes();
let formattedTime = hours + ':' + minutes.substr(-2);
//value = formattedTime
return formattedTime;
}
}
- page_xx.html
<span> </span>
- angular date forrmat 내장파이프(원하던 구현)
<span> </span>
<span> </span>
Angular 내장파이프
- 대소문자 파이프
<p>소문자 : </p>
<p>대문자 : </p>
- 날짜 파이프
<p>* </p>
- 통화 파이프
<p>* 10000.125</p>
<p>* 1.005</p>
- 퍼센트 파이프
<p>* 1.45</p>
<p>* 1.45</p>
커스텀 파이프
- 말줄임 파이프
import { Pipe, PipeTransform } from ‘@angular/core’;
@Pipe(){
name: 'shorten'
}
export class ShortenPipe implements PipeTransform {
transform(value: any, limit: number) {
if (value.length > limit) {
return value.substr(0, limit) + ' ...';
}
return value;
}
}
<p> <p>
- 콤마(,) 파이프(commaSeparatedNumber.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'commaSeparatedNumber'
})
export class CommaSeparatedNumberPipe implements PipeTransform {
transform(value:number, args:string[]) : any {
let reg = /(^[+-]?\d+)(\d{3})/;
let n = value.toString()
while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2');
return n;
}
}
- 콤마(,) 파이프(xxx.page.ts)
export class CommaSeparatedNumberComponent implements OnInit {
contents = [
230000, 200, 9999, 42343, 777888999
]
constructor() { }
ngOnInit() {
}
}
-
콤마(,) 파이프(xxx.page.html)
-
<li *ngFor="let content of contents"></li>
참고
Pipe란?
- 템플릿에서 값의 표시되는 형태를 변환해서 보여주기 위해서 사용한다.
참조
https://www.concretepage.com/angular-2/angular-2-date-pipe-example
https://bblog.tistory.com/309