How to use pipes in Component

M.Nar picture M.Nar · Dec 13, 2017 · Viewed 32.8k times · Source

I want to use the datePipe in my component. I followed the instructions here but I am met with

Error: StaticInjectorError[DatePipe]: 
StaticInjectorError[DatePipe]: 
NullInjectorError: No provider for DatePipe!

Here is my code:

Component

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

export class LivePreviewComponent implements OnInit{
    currentDate = new Date();     

    constructor(private datePipe:DatePipe) {}
    ngOnInit() {
        this.datePipe.transform(this.currentDate, 'YYYY-MM-DDTHH:mm')
    }
}

Answer

Aravind picture Aravind · Dec 13, 2017

Add to providers array in the component

@Component({
    selector: 'app-root',
    templateUrl: '...',
    providers:[DatePipe]
})

or inject it to module

@NgModule({
    providers:[DatePipe]       
})

or write a separate class extending the DatePipe and use it as a service

@Injectable()
export class CustomDatePipe extends DatePipe {
  transform(value, format) {
    return super.transform(value, format);
  }
}

and inject this to providers array

@Component({
        selector: 'app-root',
        templateUrl: '...',
        providers:[CustomDatePipe]
    })