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.

Let's Welcome Angular 9 With its New Features Debasis Saha

 As we all of us know that Google has just released its new version of Angular i.e. 9.0 just a week ago. Angular developers and the community members eagerly wait for the release of this version for a long time. Because, as announced by Google at the time of Angular 8 release, Angular 9 will be released with the features of the IVY renderer engine. So, the expectation is actually is very high for the IVY. Angular 9 is the first major release from Google in the year 2020 which is mainly focused on the toolchain and also making angular easier for the user to create different types of applications along with performance improvements. Except for this, this major version release also contains some new features and upgradation in respect of the previous versions including framework, Angular Material, Angular CLI, etc. Also, Angular 9 supports the typescript version 3.7. So with the help of a new typescript version, it is very much easy to code with faster subsequent build with the incremental flag, type checking for global this and generic type arguments.

 

New Features of Angular 9 

 
Now it’s time to discuss the major changes made in the Angular 9.
 

TypeScript 3.7.x Support

 
Angular 9 supports the Typescript 3.7 or above version. So, if we want to use Angular 9 for our application, then we need to first upgrade the Typescript version to 3.7 or above.
 

Ivy Rendering Engine

 
The most important and expected features of Angular 9 is IVY render compiler engine. Ivy is the new Angular Compiler as well as will act as a new rendering pipeline. Ivy is the code name of Angulars’s next-generation compilation and rendering pipeline. The benefit of Ivy is that it will generate considerably small-sized bundles, also can perform incremental compilation easily. So, Ivy is the basis of future innovations in the Angular world. 
  1. Ivy compiler and runtime offer many benefits over the previous compiler engine i.e. View Engine –
  2. It will provide a faster compilation.
  3. It will provide a smaller bundle size.
  4. With the help of Ivy, we can perform much faster testing operations.
  5. Provides improved CSS and style bindings
  6. Much more improved type checking in templates so that we can catch more errors at the build time and prevent the user to face those errors at runtime.
  7. Smaller bundle size compared to the current compiled bundled size.
  8. Also, the code generated by the Angular compiler is now much easier human to read and understand.
  9. The last but most favorite feature of me is that we can debug the templates.
  10. It provides improved build time and enables AOT mode for building by default.
In Angular 9, IVY is the default compiler engine for the build. If any reason, if we want to opt-out the IVY for the build process and want to continue with the previous compiler, View Engine, then we have to make the make changes in the TypeScript Configuration files as below -
  1. {  
  2.   "extends": "./tsconfig.json",  
  3.   "compilerOptions": {  
  4.     "outDir": "./out-tsc/app",  
  5.     "types": []  
  6.   },  
  7.   "files": [  
  8.     "src/main.ts",  
  9.     "src/polyfills.ts"  
  10.   ],  
  11.   "include": [  
  12.     "src/**/*.d.ts"  
  13.   ],  
  14.   "angularCompilerOptions": {  
  15.     "enableIvy": false  
  16.   }  
  17. }   

Smaller Bundle Size

 
In Angular 9, the Ivy Compiler has been designed in such a way so that it can remove the unnecessary parts of the Angular which are not being used via tree-shaking structure and as a result, it will generate less code for each Angular component in compared to the previous versions. With these improvements, small-size applications and large applications can see the most dramatic changes in the application size.
  1. The small application which does not use many Angular features can be benefited mostly from the tree-shaking structure.
  2. The Large application with a large number of components can also be benefitted from the reduced factory size.

      

Angular Core Type-Safe Changes

 
In Angular 9, we can implement faster testing with the help of the Ivy renderer engine. The TestBed is one of the APIs used for testing any angular application. In the previous Angular version, it had defined as a get function called TestBed.get() which does not accept string value after Angular 8. This is one of the breaking changes in Angular 9. Since the Angular team dedicated to rollback in this new version as it always has a very powerful impact. To solve the type of safety problem, the Angular team provide a solution called TestBed.inject() and deprecated the get function. 
  1. TestBed.get(ChangeDetectorRef) // any  
  2.   
  3. TestBed.inject(ChangeDetectorRef) // ChangeDetectorRef  
Now this improved TestBed API, inject function will perform the same type of work that the get function does earlier with the type-safe at the same time.
 

Modules with Providers Support

 
This option is mainly for library owners. If we have used ModuleWithProvider before Angular 9, at that time we may or may not have been strongly typing it. But now, from this version, we have to always use the generic ModuleWithProviders<T> type to show our module type. In the earlier version, our declaration might be looks like as below -
  1. @NgModule({ ...})   
  2. export class MyModule { static forRoot(config: SomeConfig): ModuleWithProviders {    
  3.   return {    
  4.         ngModule: SomeModule,    
  5.         providers: [{ provide: SomeConfig, useValue: config }]    
  6.   };    
  7.   }    
  8. }  
But, now in Angular 9, this will look like as below -
  1. @NgModule({ ...})    
  2. export class MyModule {    
  3.   static forRoot(config: SomeConfig): ModuleWithProviders<**SomeModule**>    
  4. {    
  5.    return {    
  6.          ngModule: SomeModule,    
  7.          providers: [{ provide: SomeConfig, useValue: config }]    
  8.    };    
  9.  }    
  10. }   

Changes in Angular Forms

 
In Angular 9, there are some changes also make in the Angular Form Version. First of all, In Angular 9 <ngForm> is no longer exists as a form selector to use Angular Form. We need to use <ng-form> to access the Angular Form in our component. Secondly, FormsModule.withConfig has been removed and now we can use FormsModule directly.
 

Dependency Injection Changes in Core

 
In the case of dependency injection, Angular 9 comes with much more improvement and functionalities. So, when we will create an @Injectable service in Angular 9, we must choose whether it should be added to the injector. In addition to the previous root and module options, now we have two more additional options –
  • platform – Mentioning providedIn: ‘platform’ option makes the service available in a special singleton platform injector which will be shared by all applications on the page.
  • any - Mentioning providedIn: ‘any’ option provides a unique instance in every module (including lazy modules) that injects the token. 

i18n Improvements

 
Angular as a JavaScript framework has been now totally supported by the internationalization and with the help of the Angular CLI, we can produce basis codes that will help us to create converter files so that we can develop an application in multiple languages. This method also further refactored by the Angular team on the Ivy engine to make it easier to implement compile-time inline.
 

Need for Faster Mobile Apps

 
As mobile usage is growing strongly around the world and the quarter of the website traffic is made up of smartphones and other mobile devices. A significant percentage of these mobile devices have access to web pages from slow internet connections. It's important to decrease downloadable resources and increase mobile user experience, but such improvements can be difficult. Ivy helps in speed application startup by reducing the size of JavaScript classes.
 

Service Worker Updates

 
In this Angular 9 version, for service workers, the deprecated versioned files option in the service worker asset group config has been removed. This means that your ngsw-config.json file that looked like this:
  1. "assetGroups": [    
  2.   {    
  3.     "name": "test",    
  4.     "resources": {    
  5.       "versionedFiles": [    
  6.         "/**/*.txt"    
  7.       ]    
  8.     }    
  9.   }    
  10. ]  
Now, in Angular 9 it looks like as below -
  1. "assetGroups": [    
  2.   {    
  3.     "name": "test",    
  4.     "resources": {    
  5.       "files": [    
  6.         "/**/*.txt"    
  7.       ]    
  8.     }    
  9.   }    
  10. ]  

How to Upgrade in Angular 9

 
To upgrade any existing Angular 8 or previous application to Angular 9, we need to perform the below steps –
  1. Angular 9 use TypeScript 3.7 so install TypeScript 3.7
  2. You need to use Node 12 or Later
  3. Now execute the upgrade command of Angular CLI -> ng update @angular/cli @angular/core 
For getting better update experience, Angular recommended updating first to the latest version of Angular 8 with the below command -
  1. ng update @angular/cli@8 @angular/core@8  
Then, we can run the update command of Angular 9 -
  1. ng update @angular/cli @angular/core
Or, alternatively, you can check your upgrade process from the below URL links - https://update.angular.io/
 
After a successful update, check the Angular version with the below command –
  1. ng version  
 New Date Range Picker

Angular Material now includes a new date range picker.

Image of the new date range picker

To use the new date range picker, you can use the mat-date-range-input and mat-date-range-picker components.

See this example on StackBlitz.

Learn more about date range selection.

Warnings about CommonJS imports

When you use a dependency that is packaged with CommonJS, it can result in larger slower applications.

Starting with version 10, we now warn you when your build pulls in one of these bundles. If you’ve started seeing these warnings for your dependencies, let your dependency know that you’d prefer an ECMAScript module (ESM) bundle.

CommonJS or AMD dependencies can cause optimization bailouts

Optional Stricter Settings

Version 10 offers a more strict project setup when you create a new workspace with ng new.

ng new --strict

Enabling this flag initializes your new project with a few new settings that improve maintainability, help you catch bugs ahead of time, and allow the CLI to perform advanced optimizations on your app. Specifically, the strict flag does the following:

  • Enables strict mode in TypeScript
  • Turns template type checking to Strict
  • Default bundle budgets have been reduced by ~75%
  • Configures linting rules to prevent declarations of type any
  • Configures your app as side-effect free to enable more advanced tree-shaking

Keeping Up to Date with the Ecosystem

As usual, we have made a few updates to the dependencies of Angular to stay synchronized with the JavaScript ecosystem.

  • TypeScript bumped to TypeScript 3.9
  • TSLib has been updated to v2.0
  • TSLint has been updated to v6

We’ve also updated our project layout. Starting with version 10 you will see a new tsconfig.base.json. This additional tsconfig.json file better supports the way that IDEs and build tooling resolve type and package configurations.

New Default Browser Configuration

We’ve updated the browser configuration for new projects to exclude older and less used browsers.

v9 Defaults

v10 Defaults

This has the side effect of disabling ES5 builds by default for new projects. To enable ES5 builds and differential loading for browsers that require it (such as IE or UC Browser), simply add the browsers you need to support in the .browserslistrc file.

Angular Team Fixit

We’ve dramatically increased our investment in working with the community. In the last three weeks our open issue count has decreased by over 700 issues across framework, tooling, and components. We’ve touched over 2,000 issues, and we plan to make large investments over the next few months, working with the community to do even more.

Deprecations and Removals

We’ve made several new deprecations and removals from Angular.

The Angular Package Format no longer includes ESM5 or FESM5 bundles, saving you 119MB of download and install time when running yarn or npm install for Angular packages and libraries. These formats are no longer needed as any downleveling to support ES5 is done at the end of the build process.

Based on heavy consultation with the community, we are deprecating support for older browsers including IE 9, 10, and Internet Explorer Mobile.

You can read more about our deprecations and removals.

Conclusion

 
In this article, we discuss the new features of Angular 9. We also discussed some breaking changes in Angular 9 means which has been changed in comparison to the previous version of angular. Also, we discussed some new features about Angular 9. I hope, this article will help you. Any feedback or query related to this article is most welcome.

Digital vs AI project in IT

 I am sure this topic is not apple to apple comparison. But looking at present technology revolutions or evolutions these are the two techno...