Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put a utility function in Angular [closed]

Tags:

angular

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.

like image 277
bernlt Avatar asked Jun 10 '26 20:06

bernlt


1 Answers

When I have alike questions I look how guys from angular, material or rxjs or any other widely-used framework do. For your case it would be https://github.com/angular/angular/blob/master/packages/core/src/sanitization/url_sanitizer.ts -- just create file for a feature and export function with descriptive name. Organizing code by features is ok. But not create bulk of everything (e.g. utils.ts), try organizing by feature.

like image 160
Stanislav Berkov Avatar answered Jun 13 '26 13:06

Stanislav Berkov