Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting angular component file into separate files

Tags:

angular

I have an angular component:

drawComponent: It has many buttons like draw rectangle, draw circle, etc. I am using paperjs which helps in actual drawing. I have some common objects which get updated. For example, I have a paperjs object which gets updated whenever I draw any shape be it circle, rectangle or any other.

My question is my drawComponent.component.tshas become too large with more than 2000 lines of code. In nodejs, I could easily split each function in a separate file, but here in angular I am not sure how to do that. Is there any way I can split my file into separate file based on the functions?

like image 247
helloworld Avatar asked Feb 16 '19 14:02

helloworld


Video Answer


2 Answers

Official file structure guidelines

You should definitely split and organize your logic into smaller files. The official Angular Style Guide recommends the following principles:

  1. Rule of One

Apply the single responsibility principle (SRP) to all components, services, and other symbols. This helps make the app cleaner, easier to read and maintain, and more testable.

  1. Small files

Consider limiting files to 400 lines of code. Consider limiting functions to 75 lines of code


How to split functionality across files

  1. Split your app into Modules, Components, Services, Directives and Pipes as described in the Style Guide.

  2. For components, directives and pipes shared across different components or modules, create a Shared Feature Module

  3. For shared functionality, create Singleton Services

  4. If it makes sense for your project, you can simply put some functions, classes or variables into separate files. It's all just TypeScript, you can export and import things easily.

like image 195
Wojciech K Avatar answered Jan 02 '23 16:01

Wojciech K


I would suggest to separate the common logic in drawingComponent.abstract.ts and implement the drawing logic in different components (e.g. circle.component.ts, triangle.component.ts) which extends the abstract class.

like image 40
smallTomato Avatar answered Jan 02 '23 17:01

smallTomato