Saturday, July 3, 2021

Top 11 Angular Best Practices to Adapt in 2021

 Angular is considered as one of the most prominent JavaScript framework for developing dynamic mobile and desktop web applications. The framework is developed by the engineers at Google and maintained by Google itself.

So, there’s no doubt about its popularity. I have been working on some large scale Angular applications and due to which I have got a chance to explore more. Getting dip inside the Angular helped me get some new and exciting tips and tricks to enhance my development skills.

Throughout the Angular App Development, I have got some new Angular practices which help in write clean code; maintain coding standard and performance.

These are something that you can’t find it from tutorial rather it is garnered from one’s own experiences. This article outlines some of the best practices Angular which have acquired during the course of Angular app development and gathered from the searches and researches. I am sure this article will add some extra feathers to development skills. Further With the latest Angular version 11 release in November 2020, i had updated some of the Angular best practices keeping the new release in mind.

Let’s Start with some some basic Angular Best Practices in 2021

1.     Use trackBy instead of ngFor

'ngFor' is a built-in template directive in Angular and it is Generally we used 'ngFor' creating a template for each item in the application. You can use 'trackBy' instead of 'ngFor' which help you by bringing unique and customized identifier each item instead of rendering the whole DOM tree.

How ‘trackBy’ Helps

When using 'ngFor', you need re-render the entire DOM tree after every change occurs in the array while using 'trackBy', you can specify the changes separately and it will help Angular to make DOM changes for the defined array.

Let’s understand this through the example here;

When you use ‘ngFor’ such as;

<ul>
<li *ngFor="let item of collection;">{{item.id}}</li>
</ul>
view rawtb.html hosted with ❤ by GitHub

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

When you use 'trackBy' functions, such as;

@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
</ul>
<button (click)="getItems()">Refresh items</button>
`,
})
export class App {
constructor() {
this.collection = [{id: 1}, {id: 2}, {id: 3}];
}
getItems() {
this.collection = this.getItemsFromServer();
}
getItemsFromServer() {
return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
}
trackByFn(index, item) {
return index; // or item.id
}
}
view rawtb1.ts hosted with ❤ by GitHub

Now, it returns as a unique identifier for each item and will be rendered only the selected item.

2.     Lazy Loading Feature Module

Utilizing lazy load the modules can enhance your productivity. Lazy Load is a built-in feature in Angular which helps developers with loading the thing which is required. For example, when you use the feature, it loads the components and other things you needed and stops other and unnecessary files to get loaded. Here’s how it functions;


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

Here the ‘LazyLoading‘ is not in place and you will end creating large and unnecessarily heavy-sized applications.

When you use;

You have used 'LazyLoad' and it helps you reduce the size of the application by abstaining from unnecessary file from loading.

3.     CDK Virtual Scroll

CDK Virtual Scroll is a very important tool at your disposal which you can utilize the gain some good performance over your development. For example, if you have a larger file more than a thousand to display at the same time, it will make the application vulnerable and likely to slow down the performances. CDK Virtual Scroll can be found inside the Angular Material Package which helps developers enhances the performance of the applications and visualize the larger file in the browser.

Here’s how it works;

1.Import Scrolling Module into your application app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ScrollingModule } from '@angular/cdk/scrolling';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ScrollingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

2. Generate 10000 items list in your app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
numbers: number[] = [];
constructor() {
for (let index = 0; index < 10000; index++) {
this.numbers.push(index);
}
}
}

3. Let’s render the list in app.component.html file

<h1 class="center">Virtual Scroll using Angular 7</h1>
<ul class="list">
<cdk-virtual-scroll-viewport style="height: 500px" itemSize="90" >
<ng-container *cdkVirtualFor="let n of numbers">
<li> {{n}} </li>
</ng-container>
</cdk-virtual-scroll-viewport>
</ul>

4. Styling
[OPTIONAL] — add styles to the application in your styles.css file

/* You can add global styles to this file, and also import other style files */
body {
font-family: 'Segoe UI', Roboto, Ubuntu, 'Open Sans', 'Helvetica Neue', sans-serif;
background-image: url(assets/images/icons-background.svg);
background-color: #507ce8;
color: #fff;
overflow: hidden;
}
ul {
max-width: 500px;
color: #333;
list-style: none;
margin: 50px auto;
padding: 10px;
}
.list li {
padding: 25px;
background: #FAFAAF;
border-radius: 5px;
margin-bottom: 5px;
text-align: center;
font-size: 32px;
font-weight: 600;
}
.center {
text-align: center;
}

You have set up the height and you all set to get the best performances.

4.     Angular Coding Styles

People never compliment the common code style, but if you have followed the standard coding style, you will be commended by your fellow developers who use your code thereafter. And, this should with every programming language you use. In the case of Angular web app development, you comply with the standard coding format and your project must have clean coding style which tends to be simple, understandable and adaptable by your fellow programmer in future.

Here’re some set of rules that you need to follow to make your project comply with the coding standard;

  • Per file, the code must not exceed from 400 lines limit
  • Per function, the code must not exceed from 75 lines
  • Utilize custom prefix to share feature area for all slider components
  • If the values of the variables are intact, 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.
  • Names of properties and methods should be in lower camel case
  • Always leave one empty line between imports and module such as third party and application imports and third-party module and custom module

5.     Folder Structure for Angular

Creating a folder structure is an extremely important factor that you should consider before initiating your project. If you have not structured the folder properly, you have invited plenty of problems which keep haunting you throughout your development process. Whether it medium and large-sized project, you will come across plenty of changes in the middle of development and your project should easily adapt the new changes made in the middle of development. And, that is possible when you have created a proper folder in place.

You can know it from this link.

6.     Prevent Memory Leaks in Angular Observable

Observable memory leaks are very common and found in every programming language, library or framework. Angular is no exception to that. Observables in Angular are very useful as it streamlines your data, but memory leak is one of the very serious issues that might occur if you are not focused. It can create the worst situation in mid of development. Here’re some of the tips which follow to avoid the leaks.

Using ‘async pipe’:

Either you can utilize subscribed observables or use ‘async pipe‘ and promise in the view. You should prevent yourself from subscribing observables in the component and binding that in view. So, the bottom line is if a complete observable technique is not in place, memory leaks are vulnerable to occur.

<ul>
<li *ngFor="let item of collection;">{{item.id}}</li>
</ul>
view rawtb.html hosted with ❤ by GitHub

Using ‘take(1):

‘take(1)’ is an operator which completes the emission by taking its value and enables the ‘take(1) not to subscribe when a new value is encountered with. It will ensure that you get the data only once. Be secure with ‘take(1)’ and avoid memory leaks easily. Here’s how it happens;


data$.pipe(take(1)).subscribe(res=>console.log(res))

Using ‘takeUntil’:

This (takeUntil) is also an operator to be used when want to monitor the second Observables and dispose of the subscription after the Observables emits the value or gets completed. In short, helps you stay fearless from being getting your Observables leaked. Here’re some examples of how you can do this;

You need to use ‘takeUntil‘ to overhaul the Subject instance (the Observable’s name) in the pipe.

Now, using a command such as “ngUnsubscribe.next()” and “this.ngUnsubscribe.complete()” in the ‘ngOnDestroy()‘ field so that it will prevent the emission from taking place as soon as the component destroyed.

Here’s how it happens;


export class SimpleComponent implements OnInit, OnDestroy {
  constructor(private route: ActivatedRoute,
              private http: Http) {
  }
  ngOnInit() {
    this.route.params
      .takeUntil(componentDestroyed(this))
      .subscribe(params => {
        // do something
      });
    this.http.get("/load")
      .takeUntil(componentDestroyed(this))
      .subscribe(result => {
        // do something
      });
  }
  ngOnDestroy() {
    // empty
  }
}

7.     Using Index.ts:

Index.ts‘ is yet another, the most significant files in Angular which helps to reduce the size of the import statement. The file supports you to export modules in it (Index.ts) while in app.module.ts, you can import the modules. Let’s understand them through the example here;

8.     Utilizing ES6 Features

Angular comes up with some important improvements in its every release. ECMAScript is one of the JavaScript versions which constantly get updated with new features and functionalities. Currently, you have ES6 which has plenty of new features and functionalities which you can utilize them in Angular.

‘let and const’ instead of ‘var’

Using ‘let and const‘ instead of ‘var‘ lets you prevent the issues and problems which you have due to var.  ‘let‘ can be utilized 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

Spread Operator:

ES6 has got ‘spread operator’ which is represented by three dots (…) which offers to help with some common tasks, though so far in ES6, it is used for arrays only. It helps ‘iterable‘, which can be strings, arrays, and sets, to get spread inside the receiver. Here’s how it works;

Example with Array;


const items = ['This', 'is', 'a', 'sentence'];

console.log(items) // Line 1

console.log(...items) // Line 2

// [ 'This', 'is', 'a', 'sentence' ] // Output 1

// This is a sentence // Output 2

Example with Object;


const obj = { name: 'Foo', age: 22 };

const newObj = { ...obj }

console.log(newObj)

// { name: 'Foo', age: 22 }

Hire Angular Developer

9.     State Management

State Management in Angular helps in managing state transitions by storing the state of any form of data. There are various state management libraries such as NGRX, NGXS, Akita, etc and all with different usages, states, and purposes. All of them are good to use, though NGXS could the preferred one as most of the developers have referred this as most usable and easy to learn the tool.

10.     Declare Variable Type Instead of Using ‘any’

While working on an Angular project, developers, generally end up typing ‘any’ to declare variables. If you are not specifying the variables and constants, they will be assumed by the value and as a result, will be assigned to it. If it happens, you are now in trouble as it will create some unintended issues, anytime.

For example;

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 wanted. In short, you can prevent this by typing the number instead of typing ‘any’.

11.     Cache API calls

When we talk about improved App performance, caching API calls is considered as one of the best Angular Practices in 2021. Caching the API calls specially in eCommerce website limits the number of server requests to fetch redundant information thus saving time and reduce load on server.

To utilize the Caching one needs to make an HTTP request and then store the results of that request in files like json, which can be served once again whenever required without requesting to server. This helps user to make fewer HTTP request to server and on return had to wait less for the response every time it required.

Final Words
Building an application requires some proper attention if you want to make it popular and adorable one. It’s a constant journey where you are the learner and you get to know something new every day. Applying these practices will help you make your development smooth and create your exciting application.

Technology’s generational moment with generative AI: A CIO and CTO guide

 Ref:  A CIO and CTO technology guide to generative AI | McKinsey 1. Determine the company’s posture for the adoption of generative AI As us...