2

I want to use 'date' pipe, but I don't want to use it inside HTML template, but inside a Typescript function, something like:

dateString.filter(date)

Do you have an idea how to do it?

2 Answers 2

3

You can use the date pipe in the component by importing it and then injecting it to your constructor, for example:

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

constructor(private datePipe: DatePipe) {}

this.datePipe.transform(dateString, 'HH:mm');
Sign up to request clarification or add additional context in comments.

Comments

2

You should inject DatePipe inside providers array of your NgModule first (As injectables should have been registered in providers array) and then you can use DatePipe inside your application as injector. You have to call its transform function to format date. Inject DatePipe it inside constructor of your component before using it DatePipe

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

Usage

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.