angular - 如何在 Component 中使用管道

标签 angular angular-pipe

我想在我的组件中使用 datePipe。我按照说明 here但我遇到了

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

最佳答案

添加到组件中的providers数组

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

或者注入(inject)模块

@NgModule({
    providers:[DatePipe]       
})

或者编写一个单独的类来扩展 DatePipe 并将其用作服务

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

并将其注入(inject)提供者数组

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

关于angular - 如何在 Component 中使用管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47783376/

相关文章:

angular - 如何扩展 ngx-translate 管道

angular - 当 proxy.conf.json 中的路径更改时,Java 应用程序无法识别更改

Angular - 响应式(Reactive)表单 - FormGroupName 里面的 FormGroupName

angular - 创建自定义管道以使用 Angular 谓词过滤值

angular - 使用 TypeScript 在 Angular 管道中使用 MapToIterable

为输入字段选择浏览器建议时,Angular Pipe 不起作用

Angular(2+) 填充 : Problems with IE - . 包括()

firefox - 图片元素在 angular2 和 firefox 中不起作用

typescript - Angular2 Http 双订阅

Angular - 不纯管道与函数