I have a function Im calling several times when I need to process a date:
dateFormat(myDate, format) {
let temp=this.datePipe.transform(myDate, format)
return(temp)
}
This just formats a date.
let niceDate=dateFormat(mydate, 'MM/dd/yyyy')
The problem is I need to call it from several components. I was looking at services it looks like its not what Im looking for (I may be wrong). Im wondering if this can be accomplished like in Node.js, but in Angular.
What is the right way to store several functions on one file, import that file and call the functions from other components?
Thanks.
You can create common utility file in that you can implement those functions which are going to be used across the application. Now you just need to import that file any component and Use that static function.
For ex:
Utils.ts file
export class Utils {
constructor() { }
dateFormat(myDate, format) {
let temp=this.datePipe.transform(myDate, format)
return(temp)
}
}
component.ts file
import { Component, OnInit} from '@angular/core';
import { Utils } from 'src/app/shared/utils/utils';
export class TestComponent implements OnInit{
myDate = new Date();
format = 'MM/DD/YYYY'
constructor() { }
covnervtDate(){
return Utils.dateFormat(this.myDate, this.format);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With