我想在我的组件中使用 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/