繁体   English   中英

angular 2:如何在Typescript函数中将字符串传递给管道?

[英]angular 2: How to pass a string to a pipe in a Typescript function?

我想使用'date'管道,但是我不想在HTML模板中使用它,而是在Typescript函数中使用它,例如:

dateString.filter(date)

你有一个想法怎么做?

您可以通过导入组件,然后将其注入到构造函数中来使用组件中的日期管道,例如:

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

constructor(private datePipe: DatePipe) {}

this.datePipe.transform(dateString, 'HH:mm');

你应该注入DatePipeproviders您的阵列NgModule第一(如注射剂应在已登记的providers阵列),那么你可以使用DatePipe您的应用程序作为喷射器内部。 您必须调用其transform函数来格式化日期。 在使用DatePipe之前,将DatePipe注入DatePipe组件的constructor

@NgModule({
   imports: [..],
   declarations: [..],
   providers: [ DatePipe, ..], //this is very much important line.
   bootstrap: [AppComponent]
})
export class AppComponent {
}

用法

//just for demo, I put filter inside constructor
constructor(private datePipe: DatePipe){ datePipe.tranform(date); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM