如何在组件中使用管道 [英] How to use pipes in Component

查看:75
本文介绍了如何在组件中使用管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在组件中使用datePipe.我按照此处的说明进行操作,但遇到了

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!

这是我的代码:

组件

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

推荐答案

添加到组件中的provider数组

Add to providers array in the component

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

或将其注入模块

@NgModule({
    providers:[DatePipe]       
})

或编写扩展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);
  }
}

并将其注入提供者数组

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

这篇关于如何在组件中使用管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆