Where to put a utility function in Angular

Viewed 10482

This is just an example working with Angular, let say I need to use a function in the component, in this case the getDay() function will be called by an event.

getDay()  {
  switch (new Date().getDay()) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
       day = "Tuesday";
       break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
}

Since I'm using Typescript, should I just create a shared folder inside components directory and inside it:

Create a component e.g: formatDate.component.ts with export class FormateDateComponent and just add my function there and import where I want?

What would be the best practice.

2 Answers

There are two ways :-

  1. create a static method in a class:-

    export Class DateHelper {
       static getDay()  {
        switch (new Date().getDay()) {
             case 0:
             day = "Sunday";
             break;
             case 1:
             day = "Monday";
             break;
             case 2:
             day = "Tuesday";
             break;
             case 3:
             day = "Wednesday";
             break;
             case 4:
             day = "Thursday";
             break;
             case 5:
             day = "Friday";
             break;
             case 6:
             day = "Saturday";
           }
        }
      }

and can use it like DateHelper.getDay() directly.

  1. way create a class and inherit it in component Foreg:-

    export class AppComponent extends DateHelper {
       constructor(){
         super();
       }
       this.getDay();
    } 

For normal methods like you have i would go with first approach.

Related