Angular Best Practices and Guidelines

Jeni Joe
2 min readJan 3, 2021
  1. Use the Angular CLI for file generation:
    This creates the component files in a folder with the component-name as <component-name>.ts|html|css|spec.ts, making the file structure easy to read.
  2. Maintain a flat folder structure without excessive nesting of subfolders.
  3. Maintain small function definitions (Angular suggests <75 lines) whenever possible for ease of testing, reuse, and maintainability.
  4. Consistent naming conventions:
    a) Upper camel case for class names and feature.type.ts (type: component, service, module, etc.)
    b) Folder naming as <feature-name>
  5. Keep third party modules in a separate module file: this helps avoid clutter in app.module.ts and encourages maintainability (e g angular-material module for all Angular Material UI imports)
  6. Single responsibility per component/service: Simplifying the folder structure and enabling developers to easily read, maintain and work collaboratively.
  7. Use service names that make sense of service provided e.g.: ItemsListService to get the list of all items.
  8. Each component should hold code only for the view. Delegate complex logic to a service which can be reused. (e.g. ConfigService to read information from a config JSON file which can then be used via dependency injection in other components/services)
  9. Talk to the server through a service (for data operations) e.g. DataService, which can be extended by other services, and in turn, can be used by multiple components/services.
  10. Use lifecycle hooks for tapping into events. e.g. ngOnInit, a life cycle hook called by Angular to indicate that Angular is done creating the component.
  11. Use constructors for dependency injection.
    Instead of using using @Inject parameter decorator with each dependency, use @Injectable() class decorator for dependencies of a service mentioned in the service class’s constructor making use of Angular’s dependency injection and keeping code concise.
  12. Isolate component-specific styling to the component’s style file, while also following a consistent naming convention. Provide style class names that make sense and are easy to understand. e.g. email-label-text.
  13. Avoid inline styling. Avoid the usage of !important for style values.

Reference: https://angular.io/guide/styleguide

--

--