0% found this document useful (0 votes)
555 views26 pages

Angular Development Best Practices Guide

The document provides best practices for Angular development. It recommends using Angular CLI to generate project structure and files, maintaining a proper folder structure with core, shared, and feature modules, following consistent coding styles, using TypeScript for type safety and tooling support, leveraging ES6 features, tracking items with ngFor using a unique identifier, breaking components into smaller reusable pieces, lazy loading modules, using index.ts files to reduce imports, moving logic out of templates into components, caching API responses, and using the async pipe with observables in templates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
555 views26 pages

Angular Development Best Practices Guide

The document provides best practices for Angular development. It recommends using Angular CLI to generate project structure and files, maintaining a proper folder structure with core, shared, and feature modules, following consistent coding styles, using TypeScript for type safety and tooling support, leveraging ES6 features, tracking items with ngFor using a unique identifier, breaking components into smaller reusable pieces, lazy loading modules, using index.ts files to reduce imports, moving logic out of templates into components, caching API responses, and using the async pipe with observables in templates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction to Angular
  • Use Angular CLI
  • Maintain Proper Folder Structure
  • Follow Consistent Coding Styles
  • Use Typescript Features
  • Leverage ES6 Features
  • Optimize with trackBy
  • Component Reusability
  • Implement Lazy Loading
  • Simplify with Index.ts
  • Avoid Logic in Templates
  • Improve Performance with Caching
  • Use Async Pipe in Templates
  • Declare Safe Strings
  • Avoid Any Type
  • State Management
  • Use CDK Virtual Scroll
  • Use Environment Variables
  • Linting with Typescript and SCSS
  • Always Document Code
  • Contact Information

Best Practices we

following in
Angular
Development

[Link]
Angular is an open-source front-end framework developed
by Google for creating dynamic, modern web applications.
Introduced in 2009, Angular’s popularity is based on its
eliminating unnecessary code and ensuring lighter and
faster apps. Having rapidly evolved from AngularJS in 2010,
the front-end framework is today used by more than 40%
of software engineers for creating user interfaces.

Angular helps build interactive and dynamic single page


applications (SPAs) with its compelling features including
templating, two-way binding, modularization, RESTful API
handling, dependency injection, and AJAX handling.
Designers can use HTML as template language and even
extend HTML’ syntax to easily convey the components of
the application. You also don’t need to rely on third-party
libraries to build dynamic applications with Angular. Using
this framework in your projects, you can reap multiple
benefits.

While Angular Documentation is the right place to get to


know best practices, this document focuses on other good
practices that are not covered in the framework’s
documentation.

2
1. Use Angular CLI

Angular CLI is one of the most powerful accessibility tools


available when developing apps with Angular. Angular CLI
makes it easy to create an application and follows all the
best practices! Angular CLI is a command-line interface
tool that is used to initialize, develop, scaffold, maintain and
even test and debug Angular applications.

So instead of creating the files and folders manually, use


Angular CLI to generate new components, directives,
modules, services, and pipes.

# Install Angular CLI

npm install -g @angular/cli

# Check Angular CLI version

ng version

3
2. Maintain proper folder structure

Creating a folder structure is an important factor we


should consider before initiating our project. Our folder
structure will easily adapt to the new changes during
development.

-- app
|-- modules
|-- home
|-- [+] components
|-- [+] pages
|-- [Link]
|-- [Link]
|-- core
|-- [+] authentication
|-- [+] footer
|-- [+] guards
|-- [+] http
|-- [+] interceptors
|-- [+] mocks
|-- [+] services
|-- [+] header
|-- [Link]
|-- [Link]
|-- [Link]
|

4
|-- shared
|-- [+] components
|-- [+] directives
|-- [+] pipes
|-- [+] models
|
|-- [+] configs
|-- assets
|-- scss
|-- [+] partials
|-- _base.scss
|-- [Link]

5
3. Follow consistent Angular
coding styles

Here are some set of rules we need to follow to make our


project with the proper coding standard.

Limit files to 400 Lines of code.

Define small functions and limit them to no more


than 75 lines.

Have consistent names for all symbols. The


recommended pattern is [Link].

If the values of the variables are intact, then declare it


with ‘const’.

Use dashes to separate words in the descriptive name


and use dots to separate the descriptive name from
the type.

Names of properties and methods should always be in


lower camel case.

Always leave one empty line between imports and


modules; such as third party and application imports
and third-party modules and custom modules.

6
4. Typescript

Typescript is a superset of Javascript, which is designed to


develop large Javascript applications. You don’t have to
convert the entire Javascript code to Typescript at once.
Migration from Javascript to Typescript can be done in
stages.

Major benefits of Typescript include:

Support for Classes and Modules

Type-checking

Access to ES6 and ES7 Features, before they are


supported by major browsers

Support for Javascript packaging and so on

Great tooling support with IntelliSense

7
5. Use ES6 Features

ECMAScript is constantly updated with new features and


functionalities. Currently, we have ES6 which has lots of
new features and functionalities which could also be
utilized in Angular.

Here are a few ES6 Features:

Arrow Functions

String interpolation

Object Literals

Let and Const

Destructuring

Default

8
6. Use trackBy along with ngFor

When using ngFor to loop over an array in templates, use it


with a trackBy function which will return a unique
identifier for each DOM item.

When an array changes, Angular re-renders the whole


DOM tree. But when you use trackBy, Angular will know
which element has changed and will only make DOM
changes only for that element.

Use ngFor

<ul>
<li *ngFor="let item of itemList;">{{[Link]}}</li>
</ul>

<ul>
<li *ngFor="let item of itemList;">{{[Link]}}</li>
</ul>

Now, each time the changes occur, the whole DOM tree will be
re-rendered.

9
Using trackBy function

<ul>
<li *ngFor="let item of itemList; trackBy: trackByFn">
{{[Link]}}
</li>
</ul>
<button (click)="getItems()">Load items</button>

export class MyApp {

getItems() { // load more items }

trackByFn(index, item) {
return index; // or [Link]
}
}

Now, it returns as a unique identifier for each item so only updated


items will be re-rendered.

10
7. Break down into small reusable
components

This might be an extension of the Single responsibility


principle. Large components are very difficult to debug,
manage and test. If the component becomes large, break
it down into more reusable smaller components to reduce
duplication of the code, so that we can easily manage,
maintain and debug with less effort.

Parent Component

Title Component

Body Component

List Component

List Component

List Component

Footer Component

11
8. Use Lazy Loading

Try to lazy load the modules in an Angular application


whenever possible. Lazy loading will load something only
when it is used. This will reduce the size of the application
load initial time and improve the application boot time by
not loading the unused modules.

Without lazy loading

// [Link]

import { WithoutLazyLoadedComponent } from


'./[Link]';

{
path: 'without-lazy-loaded',
component: WithoutLazyLoadedComponent
}

With lazy loading

// [Link]
{
path: 'lazy-load',
loadChildren: '[Link]#LazyLoadModule'
}

12
// [Link]

import { LazyLoadComponent } from './[Link]';

@NgModule({
imports: [
[Link]([
{
path: '',
component: LazyLoadComponent
}
])
],
declarations: [
LazyLoadComponent
]
})
export class LazyModule { }

13
9. Use [Link]

[Link] helps us to keep all related things together so that


we don't have to be bothered about the source file name.
This helps reduce size of the import statement.

For example, we have /heroes/[Link] as

//heroes/[Link]

export * from './[Link]';


export * from './[Link]';
export { HeroComponent } from './[Link]';

We can import all things by using the source folder name.

import { Hero, HeroService } from '../heroes'; // index


is implied

14
10. Avoid logic in templates

All template logic will be extracted into a component.


Which helps to cover that case in a unit test and reduce
bugs when there is template change.
Logic in templates

// template
<span *ngIf="status === 'inActive' || 'hold'"> Status:
Unavailable </span>

We can import all things by using the source folder name.

// component
ngOnInit (): void {
[Link] = [Link];
}

Logic in component

// template
<span *ngIf="isUnavailable"> Status: Unavailable </span>

// component
ngOnInit (): void {
[Link] = [Link];
[Link] = [Link] === 'inActive' ||
'hold';
}

15
11. Cache API calls

When making API calls, responses from some of them do


not change frequently. In those cases, we can add a
caching mechanism and store the value from an API.
When another request to the same API is made, we get a
response from the check, if there is no value available in
the cache then we make an API call and store the result.

We can introduce a cache time for some API calls the value
change, but not frequently. Caching API calls and avoiding
unwanted duplicate API calls improves speed of the
application and also ensures we do not download the
same information repeatedly.

16
12. Use async pipe in templates

Observables can be directly used in templates with the


async pipe, instead of using plain JS values. Under the
hood, an observable would be unwrapped into plain value.
When a component using the template is destroyed, the
observable is automatically unsubscribed.

Without Using async pipe

//template
<p>{{ text }}</p>

Using async pipe

// template
<p>{{ text | async }}</p>

// component
[Link] = [Link](
map(value => [Link])
);

17
13. Declare safe strings

The variable of type string has only some set of values and
we can declare the list of possible values as the type. So the
variable will accept only the possible values. We can avoid
bugs while writing the code during compile time itself.

Normal String declaration

private vehicleType: string;

// We can assign any string to vehicleType.


[Link] = 'four wheeler';
[Link] = 'two wheeler';
[Link] = 'car';

Safe string declaration

private vehicleType: 'four wheeler' | 'two wheeler';

[Link] = 'four wheeler';


[Link] = 'two wheeler';

[Link] = 'car'; // This will give the below


error

Type '"car"' is not assignable to type '"four wheeler" |


"two wheeler"'

18
14. Avoid any type

Declare variables or constants with proper types other than


any. This will reduce unintended problems. Another
advantage of having good typings in our application is that
it makes refactoring easier. If we had a proper typing, we
would get a compile-time error as shown below:

interface IProfile {
id: number;
name: string;
age: number;
}

export class LocationInfoComponent implements OnInit {


userInfo: IProfile;

constructor() { }

ngOnInit() {
[Link] = {
id: 12345,
name: 'test name',
mobile: 121212

19
}
}
}
// Error

Type '{ id: number; name: string; mobile: number; }' is


not assignable to type 'IProfile'.
Object literal may only specify known properties, and
'mobile' does not exist in type 'IProfile'.

20
15. State Management

One of the most challenging things in software


development is state management. State management in
Angular helps in managing state transitions by storing the
state of any form of data. In the market, there are several
state management libraries for Angular like NGRX, NGXS,
Akita, etc. and all of them have different usages and
purposes.

We can choose suitable state management for our


application before we implement it.

Some benefits of using state management.

It enables sharing data between different components

It provides centralized control for state transition

The code will be clean and more readable

Makes it easy to debug when something goes wrong

Dev tools are available for tracing and debugging state


management libraries

21
16. Use CDK Virtual Scroll

Loading hundreds of elements can be slow in any browser.


But CDK virtual scroll support displays large lists of
elements more efficiently. Virtual scrolling enables a
performant way to simulate all items being rendered by
making the height of the container element the same as
the height of the total number of elements to be rendered,
and then only rendering the items in view.

//Template
<ul>
<cdk-virtual-scroll-viewport itemSize="100">
<ng-container *cdkVirtualFor="let item of items">
<li> {{item}} </li>
</ng-container>
</cdk-virtual-scroll-viewport>
</ul>

// Component
export class CdkVirtualScroll {
items = [];
constructor() {
[Link] = [Link]({length: 100000}).map((_, i)
=> `scroll list ${i}`);
}

22
17. Use environment variables

Angular provides environment configurations to declare


variables unique for each environment. The default
environments are development and production. We can
even add more environments, or add new variables in
existing environment files.

Dev environment

// [Link] environment variables


export const environment = {
production: false,
apiEndpoint: '[Link]
googleMapKey: 'dev-google-map-key',
sentry: 'dev-sentry-url'
};

Dev environment

// [Link] environment variables


export const environment = {
production: true,
apiEndpoint: '[Link]
googleMapKey: 'prod-google-map-key',
sentry: 'prod-sentry-url'
};

During the application build, the environment variables are


applied automatically from the specified environment file.
23
18. Use lint rules for Typescript
and SCSS

tslint and stylelint have various inbuilt options, it forces the


program to be cleaner and more consistent. It is widely
supported across all modern editors and can be
customized with your own lint rules and configurations.
This will ensure consistency and readability of the code.

Some inbuilt options in tslint: no-any, no-magic-numbers,


no-debugger, no-console, etc.

Some inbuilt options in stylelint: color-no-invalid-hex,


selector-max-specificity, function-comma-space-after,
declaration-colon-space-after, etc.

24
19. Always Document

Always document the code as much as possible. It will help


the new developer involved in a project to understand its
logic and readability.

It is a good practice to document each variable and


method. For methods, we need to define it using multi-line
comments on what task the method actually performs and
all parameters should be explained.

/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
return [Link]()
}

We can use an extension to generate comments.

TIP: 'Document this' is a visual studio extension that


automatically generates detailed JSDoc comments for
both TypeScript and JavaScript files.a

25
contact@[Link]

Common questions

Powered by AI

Best practices for maintaining consistent code styles in Angular applications include limiting files to 400 lines of code, defining small functions with no more than 75 lines, and using consistent naming conventions such as feature.type.ts. It is also advised to use 'const' for variables with fixed values, separate descriptive names with dashes, and use lower camel case for properties and methods . These practices contribute to code quality by enhancing readability, maintainability, and ensuring that the code conforms to a uniform standard. This reduces cognitive load for developers and simplifies the process of onboarding new team members, while minimizing errors and increasing efficiency .

Avoiding logic in Angular templates is advisable as it enhances the separation of concerns by keeping the view layer clean and focusing logic within components . This practice simplifies unit testing because business logic resides in the component's TypeScript file, making it easier to cover with tests and reduce the risk of bugs due to template changes. Templates can then focus solely on presenting data and structure, which leads to more maintainable code and reduces the complexity of testing the application's view logic, as changes in the view will not directly affect the integrity of the logic .

Linting tools like TSLint and Stylelint play a critical role in Angular development by enforcing coding standards and ensuring code consistency across projects. They offer various configurable rules such as no-any, no-magic-numbers, and color-no-invalid-hex, which help prevent common mistakes and promote best practices . By highlighting issues in the development process, these tools contribute to cleaner and more cohesive code. Linting also supports automated checks during the build process, encouraging developers to adhere to team-defined coding guidelines and reducing the likelihood of runtime errors through static analysis .

Using 'trackBy' with 'ngFor' in Angular applications is recommended because it optimizes DOM rendering. Normally, when an array changes, Angular re-renders the entire DOM tree, which can be inefficient. By using 'trackBy', Angular identifies changes in array items and only re-renders the affected elements instead of the whole tree, significantly improving performance . This method is particularly useful for large lists where frequent updates are expected, as it minimizes unnecessary DOM manipulations and enhances application responsiveness.

Caching API calls in Angular applications is significant because it reduces the need for repeated API requests, which can save network bandwidth and decrease load times. By storing previously fetched data, applications can quickly retrieve information from cache rather than performing a fresh call for each request, thus speeding up response times . This technique is particularly useful when dealing with API responses that do not change frequently. It improves application performance by minimizing the server load and ensuring a more responsive user interface, ultimately enhancing the user experience and conserving server resources .

The Angular CLI offers advantages such as simplifying application initialization, development, scaffolding, maintenance, testing, and debugging. It adheres to best practices by automating the generation of components, directives, modules, services, and pipes, thereby enforcing consistent coding styles and reducing manual errors . The Angular CLI promotes a streamlined development process by creating a pre-configured project structure that enhances code organization and adaptability to future changes . As a command-line tool, it also integrates well with existing developer workflows, increasing productivity and ensuring adherence to recommended development standards.

Angular assists developers in creating single-page applications by offering features such as templating, two-way data binding, modularization, and dependency injection. Templating allows the use of HTML as a template language, extending its syntax to facilitate the expression of application components . Two-way binding synchronizes data between the model and view, ensuring changes are reflected automatically. Modularization organizes code into reusable and isolated pieces, making it easier to manage large applications. Dependency injection reduces tight coupling between components, facilitating easier testing and reuse . Together, these features enable the development of dynamic and interactive SPAs that are efficient and maintainable.

TypeScript enhances Angular development by offering type-checking, access to ES6 and ES7 features, and support for large JavaScript applications through tooling such as IntelliSense . It is designed to facilitate gradual migration from JavaScript, improving code structure through static types which help prevent runtime errors . ES6 features beneficial for Angular developers include arrow functions, string interpolation, object literals, and the use of 'let' and 'const' for variable declarations. These features simplify code syntax, improve code readability, and reduce the chance of bugs by enforcing more predictable variable scope and logic .

Lazy loading should be implemented in scenarios where there are modules or components that are not immediately needed at the start of an application. This includes feature modules that are accessed based on user interactions or specific routes. The primary benefits of lazy loading are reduced initial load times and an improved boot time by avoiding the loading of unused modules. It also optimizes resource utilization by loading parts of the application on demand, enhancing the overall user experience by making the application more responsive . As a result, it facilitates better scalability and efficient management of large applications.

It is recommended to break down large Angular components into smaller reusable ones to facilitate easier management, testing, and debugging . This approach aligns with the Single Responsibility Principle, ensuring each component serves a distinct purpose and can be developed independently of others. Advantages include reduced code duplication, improved maintainability, and enhanced modularity, making it easier to make changes and track down issues. Smaller components also enable the reuse of code across different parts of an application, promoting consistency and reducing development time . This strategy optimizes both development and application performance by focusing on modularity and reuse.

You might also like