How to use pipes in Component

房东的猫 提交于 2019-11-27 04:06:35

问题


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')
    }
}

回答1:


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]
    })



回答2:


Add in the Module providers: [DatePipe],

Add in the constructor private datePipe: DatePipe

Add in Ts file for Form Array:

const start_date = this.datePipe.transform(starttime, 'hh:mm a');
const end_date = this.datePipe.transform(endtime, 'hh:mm a');
this.Form.controls['starttime'].patchValue(start_date);
this.Form.controls['endtime'].patchValue(end_date);



回答3:


Pipes, unlike Services, are not injectable. In order to use pipe in a component, you need to create new instance of it:

ngOnInit() {
    console.log(new DatePipe().transform(this.currentDate, 'YYYY-MM-DDTHH:mm'));
}


来源:https://stackoverflow.com/questions/47783376/how-to-use-pipes-in-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!