[英]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');
你应该注入DatePipe
内providers
您的阵列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.