Organizing Angular models and interfaces

The Angular styleguide provides best practices for using classes and interfaces in applications, but it does not offer guidance on organizing interfaces and model classes.

One common question that arises is: what are the best practices for organizing files and classes?

  • Should domain classes and interfaces be stored in one file or separated into individual files?
  • Is it better to keep model classes and interfaces in separate files or together?
  • When a component or service has infrastructure classes and interfaces, how should they be organized (one file, multiple files, suffixes, etc.)?
  • Which suffixes are commonly used for model files in the Angular ecosystem?

For example, which approach is preferred:

user-service.model.ts

export enum Gender {MALE, FEMALE}

export interface UserStatus {
  id: string;
  caption: string;
}

export interface User {
  name: string;
  gender: Gender;
  status: UserStatus;
}

export interface UserListResponse extends ListResponse<User> {}

or

user-gender.model.ts

export enum Gender {MALE, FEMALE}

user-status.model.ts

export interface UserStatus {
  id: string;
  caption: string;
}

user.model.ts

export interface User {
  name: string;
  gender: Gender;
  status: UserStatus;
}

user-list-response.model.ts

export interface UserListResponse extends ListResponse<User> {}

UPD: While it may vary based on team preferences and internal agreements, the question remains: "How do other developers handle this?"

Answer №1

It ultimately comes down to personal preference.

My approach is to keep each model in its own file, grouping specific models together like UserStatus, User, and UserListResponse.

However, if the Gender enum may be used in other models/interfaces such as Customer, it should be placed in a separate file.

PS: Following the one file per class/interface approach can make it easier to identify which file corresponds to a particular class/interface when you need to make edits.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

How come Angular8's routerLinkActive is applying the active class to both the Home link and other links in the navigation bar simultaneously?

Currently, I am facing an issue with routing in my project where the home tab remains active even when I click on other tabs. I have tried adding routerLinkActiveOption as a solution, but it doesn't seem to be working for me. <ul class="nav nav-ta ...

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...

The group validator has no effect on the form's isValid status

After working with form groups in angular 5, I noticed that setting a group validator like this: this.myForm = formBuilder.group({ control1: [null, [Validators.required, Validators.minLength(3)]], control2: [null, [Validators.required, Validat ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Expanding a Typescript class with a new method through its prototype

https://i.sstatic.net/3hIOo.png I'm encountering an issue while attempting to add a method to my Typescript class using prototype. Visual Studio is giving me a warning that the function does not exist in the target type. I came across some informati ...

Angular 14 encountered an unexpected issue: There was an unhandled exception with the script file node_modules/tinymce/themes/modern/theme.min.js missing

After attempting to run ng serve, an error message appears: ⠋ Generating browser application bundles (phase: setup) ...An unhandled exception occurred: Script file node_modules/tinymce/themes/modern/theme.min.js does not exist. ⠋ Generating browser ap ...

Execute a function when a button is pressed in a React application

Currently, I am dynamically generating some HTML and have a requirement for certain "events" to trigger an onclick function. The technology stack I am using for this project involves React and TypeScript. My initial approach is as follows: function add_ev ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

Creating robust unit tests for Node.js applications with the help of redis-mock

I am facing an issue while trying to establish a connection with redis and save the data in redis using the redis-mock library in node-typescript, resulting in my test failing. Below is the code snippet for the redis connection: let client: RedisClientTyp ...

Unable to circumvent the Angular sanitize security measures

Using a wysiwyg editor (angular-editor): <angular-editor [(ngModel)]="code" name="code"></angular-editor> Underneath the editor, attempting to implement ngx-highlightjs: <pre> <code [highlight]="code" [lineNumbers]="true"></ ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...

Ways to adjust the properties within a type that are nested

I'm looking to modify a specific type in my code while retaining the other properties. Can anyone help? type Foo = { a: { b: { c: string[] ...rest } ...rest } ...rest } Is there a way to change the type of a.b.c without ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

In response to resolving an HTTP header issue with a status of 200 ok during API testing with Postman, what steps can be taken

Hello everyone, I am new to the world of Angular and facing some issues while learning. Following a tutorial on YouTube, I tried to replicate the process with a few modifications. Initially, my get API worked fine when tested with Postman, and the post API ...

When trying to call a function within a component in Angular2, it's important to remember that self.context

When I try to call a function upon instantiating an angular2 component, an error is triggered: TypeError: self.context.dummyFunc is not a function To illustrate the issue, consider the following example. Say we have this component: import { Componen ...

Improving validation in Angular reactive forms by adding custom validation onBlur

I am struggling to correctly implement the OnBlur syntax for my project. export class AppComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ published: true, credentials: this.fb.array([]), ...

What is the most effective method for structuring JSON data that is utilized by a single-page application (SPA)?

A colleague and I are collaborating on a single page application (built in React, but the framework used isn't crucial; the same query applies to Angular as well). We have a database with 2 interconnected tables: Feature Car Both tables are linked ...