Top 11 Angular Best Practices To Follow In 2020

Top 11 angular best practices to follow in 2020

Today, more than 40% of front-end developers use Angular. It is a prominent JavaScript framework for developing dynamic mobile and desktop web applications. Angular is developed and maintained by Google itself. It has gained immediate popularity and support as now static HTML pages could be more interactive. Here we have listed some of the new angular practices that will help you to write clean code, maintain coding standard and performance.

Top 11 Angular Best Practices

Angular Best Practices

1. Use Angular CLI-

It is a powerful accessibility tool available for developing apps with angular. Angular CLI eases the app development and follows all best practices. Angular CLI is a command-line interface tool which is used to initialize, develop, scaffold, maintain and test-debug angular apps. Use Angular CLI to generate new components, directives, modules, services and pipes rather than manually creating files and folders.

# Install Angular CLI
npm install -g @angular/cli
# Check Angular CLI version
ng version

2. Angular Coding Styles-

For angular web development, you should follow the standard coding format and your project must have a clean coding style which will in general be basic, understandable and adaptable by your programmer in future. Here are some rules that you should follow-

  • Limit files to 400 lines of code
  • Per function, the code must not exceed from 75 lines
  • Use custom prefix to share feature area for all slider components
  • Have consistent names for all symbols. The suggested pattern is feature.type.ts
  • If the values of the variables are intact, then declare it with ‘const’.
  • If you often prefix names for field, table, and database, then you need to avoid this for Interface names like iShape, AbastractShape, etc.
  • Use dash to separate words in descriptive name and use dots to separate descriptive name from the type
  • Names of properties and methods should be in lower camel case
  • Leave one empty line between imports and modules like third party and application imports, third party modules and custom modules.

3. Follow Proper Folder Structure-

Creating a folder structure is an important factor to consider before project initialization. A messy folder welcomes many problems which continue frequenting you all through your development process. Regardless of whether it is a medium and large-sized project,  you will go over a lot of changes being developed and your project should easily adapt the new changes made in the middle of development. And, that is possible when you have made an appropriate folder in place.

-- app
|-- modules
|-- home
|-- [+] components
|-- [+] pages
|-- home-routing.module.ts
|-- home.module.ts
|-- core
|-- [+] authentication
|-- [+] footer
|-- [+] guards
|-- [+] http
|-- [+] interceptors
|-- [+] mocks
|-- [+] services
|-- [+] header
|-- core.module.ts
|-- ensureModuleLoadedOnceGuard.ts
|-- logger.service.ts
|-- shared
|-- [+] components
|-- [+] directives
|-- [+] pipes
|-- [+] models
|-- [+] configs
|-- assets
|-- scss
|-- [+] partials
|-- _base.scss
|-- styles.scss

4. Use Index.ts-

Index.ts is helpful to keep related things together with the goal that we don’t need to be bothered about the source file name. It helps to reduce the size of import statement. Let us see an example-

We need /heroes/index.ts as-

export * from './hero.model';
export * from './hero.service';
export { HeroComponent } from './hero.component';

You can import all things by using source folder name.

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

5. Lazy Loading Feature Module-

Using lazy load the modules can improve your productivity. It is a built-in feature in Angular that helps developers to load the required things. For instance- When you use the feature, it loads the components and other things that you need and stops unnecessary files to get loaded.

Here’s how it functions;

// app.routing.ts
{ path: 'not-lazy-loaded', component: NotLazyLoadedComponent }

Here the ‘LazyLoading’ isn’t set up and you will wind up making large and superfluously heavy-sized applications.

When you use ‘LazyLoad’ and it reduces the size of the application by abstaining from unnecessary file from loading.

6. Use ES6 Features-

ECMAScript is updated with new features and functionalities. Use ES6 that  has a lot of new features and functionalities which could be used in Angular. 

New features of ES6-

  • Arrow Functions
  • String interpolation
  • Object Literals
  • Let and Const
  • Destructuring
  • Default

Using ‘let and const’ instead of ‘var’-

Using ‘let and const‘ instead of ‘var’ prevents the issues and problems which you have due to var. ‘let’can be used in a normal situation and the value does not receive any changes, then ‘const’ should be in place. Here’s the example;

let temp;
Const pi = 3.14159

7. State Management-

It manages the state transitions by storing the states of any form of data. NGRX, NGXS, Akita, are some of the state management libraries with different usages, states and purposes. NGXS could be the preferred and easy to learn for developers. 

8. Avoid Logic In Templates-

All template logic will be extracted into a component which helps to cover that in a unit test and reduce bugs when there is template change.

Logic in templates

// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;

Logic in component

// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;
this.isUnavailable = this.status === 'inActive' || 'hold';

9. Use async pipe In Templates-

Rather than using plain JS values, observables can be directly used in templates with async pipe. An observable would be unwrapped into plain value. When a component using the template is destroyed, observable is automatically unsubscribed.

Without Using async pipe

{{ text }}

Using async pipe

// template
{{ text | async }}
// component
this.text = observable.pipe(
map(value => value.item)

10. Use trackBy With ngFor-

When you are going to use ngFor to loop over an array, use it with a trackBy function that returns a unique identifier for each DOM item. When the 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

<li *ngFor="let item of itemList;">{{}}</li>

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

Using trackBy function

  <li *ngFor="let item of itemList; trackBy: trackByFn">
Load items(button)
export class MyApp {
getItems() { // load more items }
trackByFn(index, item) {
return index; // or

Now, it returns as a unique identifier for each item, hence just updated items will be re-rendered.  

11. Declare Variable Type Instead Of Using ‘any’-

Generally when developers work on Angular projects, they use ‘any’ to declare variables. If you are not specifying the variables and constants, they will be assumed by the value and thus, will be assigned to it. If it occurs, you are now in a problem as it will create some unintended issues, anytime. 

For instance;

If you code like this;

const x = 1;
const y = 'a';
const z = x + y;
console.log(`Value of z is: ${z}`

// Output
Value of z is 1a

You are supposed to perfect output.

And, if you code like this;

const x: number = 1;
const y: number = 'a';
const z: number = x + y;

// This will give a compile error saying:

Type ‘”a”‘ is not assignable to type ‘number’.

const y: number

You may not get all you needed. To put it plainly, you can prevent this by typing the number instead of typing ‘any’.

Know the new features and updates of Angular 10 at- Amazing New Features And Updates Of Angular 10.

Final Words-

Application development needs proper attention to make it successful and popular. Effective development with best practices helps you to achieve the goal you want to. Apart from the above mentioned best practices, there are plenty of others that you get through your experience.

If you are thinking to develop an app with angular, connect with solace experts. You can hire angular developers of Solace team to help you through development. Connect with solace and get a free quote for effective and efficient app development. We will be happy to help you.

Related Post