2016-12-22 7 views
4

HTML에서뿐 아니라 서비스 및 지시문 스크립트 파일에서 angular2의 date 파이프를 사용해야합니다.서비스 및 지시문 스크립트 파일에서 angular2 built-in date 파이프를 사용하는 방법

아이디어가 있습니까?

일부 제한 사항을 코드를 업로드 할 수 없습니다. 죄송합니다. 이 같은

+1

@Community, 제가 질문하고자하는 것은뿐만 아니라 구성 요소 서비스 및 지침에 angular2 날짜 파이프를 사용하는 방법이다 질문 https://stackoverflow.com 서로 다른 인/questions/36816548/2-in-a-a-a-a-a-pipe-in-a-a-2를 사용하십시오. –

답변

18

CommonModule은 공급자로 내 보내지 않으므로 직접해야합니다. 이것은 그리 복잡하지 않습니다.

1) 가져 오기 DatePipe :

import { DatePipe } from '@angular/common'; 

2) 모듈의 공급 업체에 DatePipe 포함 :

NgModule({ 
    providers: [DatePipe] 
}) 
export class AppModule { 
} 

또는 구성 요소의 공급 업체 :

@Component({ 
    selector: 'home', 
    styleUrls: ['./home.component.css'], 
    templateUrl: './home.component.html', 
    providers: [DatePipe] 
}) 
export class HomeComponent { 
... 

3) 구성 요소의에 주입 다른 서비스와 마찬가지로 생성자 :

constructor(private datePipe: DatePipe) { 
} 

4)를 사용하여

ngOnInit() { 
    this.time = this.datePipe.transform(new Date()); 
} 
+0

대단히 감사합니다. @Alexander, 저에게 적합하지만 DatePipe '@ Anger/common/src/pipes'에서이'import {DatePipe} '처럼 실행하지 않으면 webstorm에 오류가 표시됩니다. –

+0

@ 래리 첸 (LarryChen), 이것은 설치에있어 다른 문제가 있음을 의미합니다. 이전 버전의 ng2 또는 WebStorm을 사용 중일 수 있습니다. –

+0

내 버전 :' "@ angle/common": "^ 2.3.0"', webstorm : 2016.3.2 –

4

시도 뭔가 :이 도움이 될 것입니다

new DatePipe().transform(myDate, 'yyyy-dd-MM'); 

희망.

+0

감사합니다. Avnesh, DatePipe의 생성자가'constructor (_locale : string)'인 것을 발견했습니다. 제안 사항이 매개 변수를 놓친 것이지만 어쨌든 그것은 많은 영감을 받았습니다. –

+2

두 답변을 모두 포함하는 샘플 코드 'new DatePipe ('en-US'). 변형 (myDate, 'yyyy-dd-MM'); ' – Chimu