Reputation: 651
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')
}
}
Upvotes: 36
Views: 40842
Reputation: 421
if you using a standalone component and have no ngModule
in your application, and want to use DatePipe
in your services, so just add the DatePipe
in providers
array in the component which is using that service.
In the component that service is used.
@Component({
selector: 'app-counter',
standalone: true,
imports: [NgClass, NgStyle, NgIf],
providers: [DatePipe], // here
templateUrl: './counter.component.html',
styleUrl: './counter.component.scss',})
Upvotes: 0
Reputation: 187
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);
Upvotes: 11
Reputation: 41581
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]
})
Upvotes: 67