I am trying to build utilities services (classes) for an angular project. Utility classes have static functions (so we don’t need to create unnecessary objects). One example:
import { Injectable } from '@angular/core'; @Injectable() export class DateService { constructor() { } public static parseDate(dateString: string): Date { if (dateString) { return new Date(dateString); } else { return null; } } }
In my component class file, I then import it like this:
import { DateService } from '../utilities/date.service';
and inside the class code, how it works:
ngOnInit():void { let temp = DateService.parseDate("2012/07/30"); console.log(temp);
However, I would like to be able to use these utility functions in an angular html template, for example:
<label for="date">Date</label> <input type="date" class="form-control" id="date" required [value]="event.date | date: 'yyyy-MM-dd'" (input)="event.date=DateService.parseDate($event.target.value)" name="date">
Unfortunately, this does not work; giving the error "Unable to read property" parseDate "from undefined".
Now I can move the parseDate function to the component class, and this works fine (with the necessary change in the template, of course) ... however, if I have a bunch of components, they would all have their own parseDate function, and I think that we all know that a bad idea that does not scale well. (please ignore the trivial nature of the parseDate function)
Also, although I really don't want to instantiate an object just to run a static function, I try it with the actual dependency injection. Add it to the providers array and create an instance in the constructor - for example:
constructor(private _dateService: DateService) { }
and then changing my template to:
label for="date">Date</label> <input type="date" class="form-control" id="date" required [value]="event.date | date: 'yyyy-MM-dd'" (input)="event.date=_dateService.parseDate($event.target.value)" name="date">
This also fails, this time with the error "self.context._dateService.parseDate is not a function". Removing the “statics” from the function fixes the problem, and I can move on, but I still need to create something just to run, which should only be a static function. Of course, there is a better way.
Thoughts?