Search

Advantages and Disadvantages of Angular

What is Angular? Angular is a frontend web application development framework based on TypeScript, built by folks at Google and heavily contributed to by a huge community of developers around the world. It is a Single Page Application (SPA) framework, which means that Angular is capable and is primarily used to build single page web applications or SPAs.Angular logoAngular is developed by the same team of individuals that developed the popular framework AngularJS. The modern Angular requires you to have knowledge of the Typescript language which is a strict syntactical superset of JavaScript and adds optional static typing and some other features to the language that otherwise JavaScript lacks. The AngularJS framework was re-written and called "Angular 2", but this led to a lot of confusion and panicwithin the developer community. To clarify, the Angular team started to use separate terms for each framework. At this point, "AngularJS" now referred to the 1.X versions and "Angular" without the "JS" referred to versions 2 and up. Since then, all the versions of the framework other than 1.X are just called Angular. You can, however, mention the version number to be more precise. TypeScript is designed for development of large applications and transpiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. So, you can still use JavaScript in your TypeScript code files, but please do not do that. In this article, we will take a closer look at how Angular has evolved into one the mostpopular web development frameworks and understand its pros, cons, features and more. We will leave you with a few quick tips and suggest how you can get started with understanding Angular indepth to achieve mastery over the subject. History of Angular AngularJS was the first version of the framework, created by Google, that first came out in 2010and it shook the developer community. There were so many amazing features that AngularJS offered. Most talked and loved of all the features that it offered was two-way binding between the view and the model.  So, it let us developers get rid of a lot of useless code to set up bindings and keep the view and model in sync at all times. AngularJS was golden. AngularJS became very popular within the developer community and was widely adopted.It received a lot of traction. Still, the team decided to take another step further and developed a new version which was initially named Angular 2 but later was called Angular without the “JS” part. Soon after, in 2014, Angular 2.0 was announced which was a complete rewrite of the framework from scratch and unlike AngularJS that used JavaScript as the primary language, it used TypeScript. A final version of the framework, Angular 2, was released in 2016. Later, it was renamed to Angular to avoid conflicts and confusions within the developer community.  A lot of new changes were brought in and developers had to learn it all over again which was a tough change but was welcomed by the community. Angular opted for semantic versioning and from now on, all versions of Angular will just be called Angular. Near the end of 2016, Angular 4 came out (yeah, they skipped Angular 3 to avoid some conflicts and confusions). With a few more major versions and performance upgrades in each version, we have now arrived (at the time of writing of this article) to Angular 9.  Angular 9 has better than ever performance and latest features. In these intermediate versions, there have been updates to the performance, CLI features, progressive-web app features, router, and a lot more. They even upgraded to a better rendering engine in Angular 9. Angular 10, a major upgrade to the popular web development framework, has reached the release candidate stage, with six release candidates published as of June 17, 2020. The upgrade to the Google-developed, TypeScript-based framework focuses more on ecosystem improvements than new features. Advantages of Angular Angular hascome a long way since 2012. There are benefits to using the framework and there are some drawbacks as well, especially if you are a beginner. Let us talk about the good things first. Maintained by Google The best things about Angular is that it is developed and maintained by Google. As it is backed by a trusted company, trust is well established within the community. Developers believe in the framework and in the fact that it will be maintained, and issues will be resolved, of course withthe help of community contributions. Large community and ecosystem Angular is actively maintained and has a large community and ecosystem. You can find lots of material on this framework as well as many useful third-party tools. Currently, Angular has around over 63K stars on GitHub, a clear indication of the popularity of the framework. Github   Two-way Data binding Two-way data binding in Angular will help users to exchange data from the component to view and from view to the component. It will help users to establish communication bi-directionally. Two-way data binding can be achieved using a ngModel directive in Angular. This ensures that the model and the view are always kept in sync without any extra effort. Use of TypeScript Angular opted for TypeScript as the primary programming language. TypeScript adds a lot of syntactic sugar to JavaScript. With TypeScript, we also get several productivity benefits. In editors like VS Code and WebStorm, we have access to robust code help (intellisense) as we type, making it easier to discover types, the features they offer, and most importantly the common syntactical errors.TypeScript is a typed superset of JavaScript that compiles to plain JavaScriptSupport for i18n Internationalization is the process of making sure that an application is designed and prepared to be used in regions with different languages. Localization is the process of translating your internationalized app into specific languages for particular locales. Angular can take care of most things when it comes to multiple languages. Dates, numbers, times, and other things are easily taken care of based on the locale. On top of that, the Angular CLI allows us to install the @angular/localize package and generate most of the boilerplate code necessary. Support for lazy loading An Angular module is a logical unit of code that performs a certain task or takes care of a certain responsibility in the application. A normal Angular application can be broken down into multiple modules, where each module is delegated a certain responsibility. A module can comprise of components, pipes, directives or more modules.  Breaking down an application into modules not only allows to easily manage an application as it grows, but also offers huge performance advantages. Instead of loading all the application code at once in the browser which may cause more loading time and a slower initial render of the web page, it loads only what is necessary. This is called lazy loading.  Only the modules that are required are loaded initially and more modules or rather chunks of code are loaded as an when required. This offers seamless performance and smaller loading times. Every Angular app has at least one NgModule class, the root module which is responsible to bootstrap the project. Conventionally, it is named AppModule and itresides in a file named app.module.ts.  Dependency injection Dependency injection or DI is one of the most important application design patterns and Angular has its own dependency injection framework. It is typically used in the design of Angular applications to increase their efficiency and modularity. This is closely related to the previous point - modularization of the Angular app.   Dependencies are services or objects that a class needs to perform its function. The class requests services from an external resource, generally another module or class in this case, instead of creating them themselves. This allows us to delegate single responsibility to each module. The advantage of dependency injection design pattern is to divide the task into multiple services. The class will not create the dependent object itself, rather it will be created and injected by an Angular injector. Dependency Injection is technique that is used to reduce the coupling amongst various components of an application. Looser coupling allows for better testability and maintainability. Powerful Router Routing or in-app navigation in Angular is taken care of by the Angular Router. It is a module available in the @angular/router package. Angular router is a very powerful and flexible navigational service. It usesa component called router-outlet to load various components into the view depending upon the URL in the browser.  Angular Router has built-in support for lazy loading components, so the modules are loaded from the server as the user navigates within the app. Huge apps have a lot of benefits because of this feature.  Support for Ionic Angular was the first framework that was supported by the Ionic framework. It allows building cross-platform mobile applications for Android and iOS using the Ionic components and Angular code. As of now, more frameworks like ReactJS and VueJS are also supported but still, Angular is widely used with the Ionic framework for mobile application development.Angular is widely used with the Ionic framework for mobile app developmentAvailability of packages There is a huge repository of open-source packages available for Angular developers. Some of the most important packages are NgBootstrap, Angular Google Maps, NgRx, NgTranslate, AngularFire, NgxTextEditor, Angular Material, Ng2 Pdf Viewer, NgxCharts, and many more. Some of these packages are maintained by the official Angular team and most of these are taken care of by the community of developers as well. It is most likely that if you are looking to build a complex feature or a component for your application, a package already exists for you, so why reinvent the wheel? Disadvantages of Angular So, we have seen the good things about Angular, but there is another side to the story as well. Let us talk about some of the downsides of using one of the most popular web development framework. Steeper learning curve While Angular is great, it may not be the case for a complete beginner. Even if you have experience with HTML, CSS and JS, you may feel a little bit uncomfortable with the steep learning curve that it has. It brings its own notions and philosophy to the table that you need to work around.  Angular is an opinionated framework which means that it has its own rules that developers need to learn and follow. This can be a good and a bad thing, but the learning curve can be uncomfortable for total beginners. I would recommend that you stay patient and start slow. Slow and steady! Limited SEO Capabilities Angular is just great for building powerful single-page web applications. However, as with all single-page web applications, there is a disadvantage when it comes to search engine optimization.   Usually single-page applications are rendered on the client side and therefore web crawlers of search engines like Google and Bing are not able to see the complete structure and content of the individual pages of the websites. With this limitation in place,it is not possible to list your website correctly in search engine results.  However, there are techniques and packages to make this work, but it is an extra effort in terms of development. Angular universal is a way to render the Angular application of the server itself. The technology enables server-side rendering for Angular applications. Angular Universal generates static application pages on the server through a process called server-side rendering. While Angular universal takes care of most aspects, it still requires a lot of setup. If you prefer to do it all manually, there are documents available to help you do that but there are gotchas that you need to watch out for. Too many versions Angular has been evolving. It started out as a JavaScript framework AngularJS and now the current version is Angular 9 with a total of 6 major releases in between. This can cause confusion especially for beginners. Many a time, beginners struggle to understand the versioning. I have seen students learning a version of the framework, latest at the time, and by the time they finish their first project, a new major release is out. This causes trust issues. Developers, at times, feel that they must keep working on their apps and resolve version conflicts and compatibility issues. Decline in popularity With the advent of newer frameworks like VueJS and ReactJS, Angular has seen a downfall in its popularity. Just a few years ago, developers were mainly debating on whether they should be using Angular or React for their projects. But over the course of the last couple of years, we saw a growth of interest in a third player called VueJS or Vue.js. While the job market in Angular continues to expand, it has been observed that the popularity of the framework has been declining. I believe that too many versions is one of the main issues that the framework needs to address. Lot of boilerplate code If you are building a simple app, there is a lot of boilerplate code that the application requires. Although with tools like StackBlitz, it has become easier to try code ideas and experiment without having to install anything on your computer, but if you decide to start developing an Angular app on your system, you need to install a bunch of things and the most simple “Hello World!” application will have a lot of code that you do not care about. What’s new in Angular 9? Let us take a closer look at what is in store for us in the Angular 9 version of the framework. We will delve into the latest version of Angular 10, released in June 2020, in a separate blog post. Step-by-step guide The official Angular website offers a step-by-step guide on how to upgrade your existing apps to the latest version. GuideIvy, the next-gen compilation and rendering engine Ivy is the code name for Angular's next-generation compilation and rendering engine. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine. You can, however, disable Ivy if you still want to use View Engine for your app. It is a huge milestone for the framework. Ivy offers faster build times and small build sizes. It also offers a new change detection system.The important point is that we don’t have to change how we write our applications. Ivy aims to be compatible with the existing applications. Ivy is going to be smaller, simpler, and faster as quoted by the Angular team.  In the demo shown by Miško Hevery, the creator of the AngularJS framework,in ngConf 2018, the Hello World application was merely 3.2KB which is significantly small although 3.2KB is the result after minification + gzip.Total bundle SizeIvy compiles one file at a time and therefore follows the locality principle. Ivy looks at a component's template when generating the compiled output. This process leads to faster compilation. Ivy makes sure that, if you are not using something in Angular, it does not get included. Since Ivy pipelining is simplified, templates will be part of the stack trace.  No more cryptic error messages when something is broken in our template syntax as we will see the exact line number where the error is. The Ivy compiler has been designed to remove parts of Angular code that aren’t being used via a mechanism called tree-shaking and to generate less code for each Angular component. With these improvements, small apps and large apps can see the most dramatic size savings. Angular ahead-of-time (AOT)  In Angular 9, AOT is enabled for Dev build as well. The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code.  Compiling your application during the build process provides a faster rendering in the browser. AOT allows faster rendering of the application and also makes sure that there are a lot less asynchronous requests. According to the docs, AOT compilation with Ivy is faster and should be used by default. Lazy loading components Before Angular 9, we could only lazy load modules. Now, you can also lazy load components. It is a great way to shrink the size of your main bundle and boost the initial load of your application. Lazy loading of single components has not been possible so far. But things have changed with Ivy.  Works with TypeScript 3.6 and 3.7 The latest version of the TypeScript is 3.7 and Angular 9 is updated to work with TypeScript 3.6 and 3.7. Angular 9 supports usage of the same TypeScript Diagnostics format for the TypeScript Compiler diagnostics, which will generate more descriptive error messages. According to the official docs - “In TypeScript 3.7, when opening a project with dependencies, TypeScript will automatically use the source . ts / . tsx files instead. This means projects using project references will now see an improved editing experience where semantic operations are up-to-date and “just work”. SupportscCSS variables or custom properties Angular 9 supports CSS variables or custom properties. CSS variables or custom properties allowsdevelopers to define their own variables for CSS values that can be shared between components and style rules.  CSS custom properties or CSS variables allow the CSS property values to be changed at runtime. The possibility that the CSS custom properties can be updated during runtimeopens the opportunity to easily create themes for newer Angular application.  Angular:Quick tips and facts Angular is a framework used for front-end development. This involves the client-side of the application and has little to do with the back end. Angular is best utilized for completing advanced, large-scale projects under the direction of a seasoned developer. Angular is created for enterprise-scale applications. Angular elements can be added to projects that were built using a different platform, such as React or Polymer. Angular is supported by Google. This program is not up to par with SEO best practices, so if your primary focus is search engine optimization, opt for a different platform. Angular is a JavaScript framework—not a JS Library.Angular ranked second in “most used technology” in the Stack Overflow Survey of 2018.  How to get started with Angular?Are you ready to take on the best and become a master of the Angular framework? Check out the Angular Training and Certification which comes with instructor-led live training and real-life project experience.  This training will help you understand Angular in-depth and help you achieve mastery over the subject. Master Angular programming with our in-depth online courses. Explore them now!

Advantages and Disadvantages of Angular

13K
Advantages and Disadvantages of Angular

What is Angular? 

Angular is a frontend web application development framework based on TypeScript, built by folks at Google and heavily contributed to by a huge community of developers around the world. It is a Single Page Application (SPA) framework, which means that Angular is capable and is primarily used to build single page web applications or SPAs.

Angular logoAngular logo

Angular is developed by the same team of individuals that developed the popular framework AngularJS. The modern Angular requires you to have knowledge of the Typescript language which is a strict syntactical superset of JavaScript and adds optional static typing and some other features to the language that otherwise JavaScript lacks. 

The AngularJS framework was re-written and called "Angular 2", but this led to a lot of confusion and panicwithin the developer community. To clarify, the Angular team started to use separate terms for each framework. At this point, "AngularJS" now referred to the 1.X versions and "Angular" without the "JS" referred to versions 2 and up. Since then, all the versions of the framework other than 1.X are just called Angular. You can, however, mention the version number to be more precise. 

TypeScript is designed for development of large applications and transpiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. So, you can still use JavaScript in your TypeScript code files, but please do not do that. 

In this article, we will take a closer look at how Angular has evolved into one the mostpopular web development frameworks and understand its pros, cons, features and more. We will leave you with a few quick tips and suggest how you can get started with understanding Angular indepth to achieve mastery over the subject. 

History of Angular 

AngularJS was the first version of the framework, created by Google, that first came out in 2010and it shook the developer community. There were so many amazing features that AngularJS offered. Most talked and loved of all the features that it offered was two-way binding between the view and the model.  

So, it let us developers get rid of a lot of useless code to set up bindings and keep the view and model in sync at all times. AngularJS was golden. AngularJS became very popular within the developer community and was widely adopted.It received a lot of traction. Still, the team decided to take another step further and developed a new version which was initially named Angular 2 but later was called Angular without the “JS” part. 

Soon after, in 2014, Angular 2.0 was announced which was a complete rewrite of the framework from scratch and unlike AngularJS that used JavaScript as the primary language, it used TypeScript. A final version of the framework, Angular 2, was released in 2016. Later, it was renamed to Angular to avoid conflicts and confusions within the developer community.  

A lot of new changes were brought in and developers had to learn it all over again which was a tough change but was welcomed by the community. Angular opted for semantic versioning and from now on, all versions of Angular will just be called Angular. 

Near the end of 2016, Angular 4 came out (yeah, they skipped Angular 3 to avoid some conflicts and confusions). With a few more major versions and performance upgrades in each version, we have now arrived (at the time of writing of this article) to Angular 9.  

Angular 9 has better than ever performance and latest features. In these intermediate versions, there have been updates to the performance, CLI features, progressive-web app features, router, and a lot more. They even upgraded to a better rendering engine in Angular 9. 

Angular 10, a major upgrade to the popular web development framework, has reached the release candidate stage, with six release candidates published as of June 17, 2020. The upgrade to the Google-developed, TypeScript-based framework focuses more on ecosystem improvements than new features. 

Advantages of Angular 

Angular hascome a long way since 2012. There are benefits to using the framework and there are some drawbacks as well, especially if you are a beginner. Let us talk about the good things first. 

Maintained by Google 

The best things about Angular is that it is developed and maintained by Google. As it is backed by a trusted company, trust is well established within the community. Developers believe in the framework and in the fact that it will be maintained, and issues will be resolved, of course withthe help of community contributions. 

Large community and ecosystem 

Angular is actively maintained and has a large community and ecosystem. You can find lots of material on this framework as well as many useful third-party tools. Currently, Angular has around over 63K stars on GitHub, a clear indication of the popularity of the framework. 

Angular is one of the most popular frameworks

Github   

Two-way Data binding 

Two-way data binding in Angular will help users to exchange data from the component to view and from view to the component. It will help users to establish communication bi-directionally. Two-way data binding can be achieved using a ngModel directive in Angular. This ensures that the model and the view are always kept in sync without any extra effort. 

Use of TypeScript 

Angular opted for TypeScript as the primary programming language. TypeScript adds a lot of syntactic sugar to JavaScript. With TypeScript, we also get several productivity benefits. In editors like VS Code and WebStorm, we have access to robust code help (intellisense) as we type, making it easier to discover types, the features they offer, and most importantly the common syntactical errors.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScriptTypeScript is a typed superset of JavaScript that compiles to plain JavaScript

Support for i18n 

Internationalization is the process of making sure that an application is designed and prepared to be used in regions with different languages. Localization is the process of translating your internationalized app into specific languages for particular locales. Angular can take care of most things when it comes to multiple languages. Dates, numbers, times, and other things are easily taken care of based on the locale. On top of that, the Angular CLI allows us to install the @angular/localize package and generate most of the boilerplate code necessary. 

Support for lazy loading 

An Angular module is a logical unit of code that performs a certain task or takes care of a certain responsibility in the application. A normal Angular application can be broken down into multiple modules, where each module is delegated a certain responsibility. A module can comprise of components, pipes, directives or more modules.  

Breaking down an application into modules not only allows to easily manage an application as it grows, but also offers huge performance advantages. Instead of loading all the application code at once in the browser which may cause more loading time and a slower initial render of the web page, it loads only what is necessary. This is called lazy loading.  

Only the modules that are required are loaded initially and more modules or rather chunks of code are loaded as an when required. This offers seamless performance and smaller loading times.
 
Every Angular app has at least one NgModule class, the root module which is responsible to bootstrap the project. Conventionally, it is named AppModule and itresides in a file named app.module.ts.  

Dependency injection 

Dependency injection or DI is one of the most important application design patterns and Angular has its own dependency injection framework. It is typically used in the design of Angular applications to increase their efficiency and modularity. This is closely related to the previous point - modularization of the Angular app.  
 
Dependencies are services or objects that a class needs to perform its function. The class requests services from an external resource, generally another module or class in this case, instead of creating them themselves. This allows us to delegate single responsibility to each module.
 
The advantage of dependency injection design pattern is to divide the task into multiple services. The class will not create the dependent object itself, rather it will be created and injected by an Angular injector. Dependency Injection is technique that is used to reduce the coupling amongst various components of an application. Looser coupling allows for better testability and maintainability. 

Powerful Router 

Routing or in-app navigation in Angular is taken care of by the Angular Router. It is a module available in the @angular/router package. Angular router is a very powerful and flexible navigational service. It usesa component called router-outlet to load various components into the view depending upon the URL in the browser.  

Angular Router has built-in support for lazy loading components, so the modules are loaded from the server as the user navigates within the app. Huge apps have a lot of benefits because of this feature.  

Support for Ionic 

Angular was the first framework that was supported by the Ionic framework. It allows building cross-platform mobile applications for Android and iOS using the Ionic components and Angular code. As of now, more frameworks like ReactJS and VueJS are also supported but still, Angular is widely used with the Ionic framework for mobile application development.

Angular is widely used with the Ionic framework for mobile app developmentAngular is widely used with the Ionic framework for mobile app development

Availability of packages 

There is a huge repository of open-source packages available for Angular developers. Some of the most important packages are NgBootstrap, Angular Google Maps, NgRx, NgTranslate, AngularFire, NgxTextEditor, Angular Material, Ng2 Pdf Viewer, NgxCharts, and many more. Some of these packages are maintained by the official Angular team and most of these are taken care of by the community of developers as well. It is most likely that if you are looking to build a complex feature or a component for your application, a package already exists for you, so why reinvent the wheel? 

Disadvantages of Angular 

So, we have seen the good things about Angular, but there is another side to the story as well. Let us talk about some of the downsides of using one of the most popular web development framework. 

Steeper learning curve 

While Angular is great, it may not be the case for a complete beginner. Even if you have experience with HTML, CSS and JS, you may feel a little bit uncomfortable with the steep learning curve that it has. It brings its own notions and philosophy to the table that you need to work around.  

Angular is an opinionated framework which means that it has its own rules that developers need to learn and follow. This can be a good and a bad thing, but the learning curve can be uncomfortable for total beginners. I would recommend that you stay patient and start slow. Slow and steady! 

Limited SEO Capabilities 

Angular is just great for building powerful single-page web applications. However, as with all single-page web applications, there is a disadvantage when it comes to search engine optimization.  
 
Usually single-page applications are rendered on the client side and therefore web crawlers of search engines like Google and Bing are not able to see the complete structure and content of the individual pages of the websites. With this limitation in place,it is not possible to list your website correctly in search engine results.  

However, there are techniques and packages to make this work, but it is an extra effort in terms of development. Angular universal is a way to render the Angular application of the server itself. The technology enables server-side rendering for Angular applications. Angular Universal generates static application pages on the server through a process called server-side rendering. 

While Angular universal takes care of most aspects, it still requires a lot of setup. If you prefer to do it all manually, there are documents available to help you do that but there are gotchas that you need to watch out for. 

Too many versions 

Angular has been evolving. It started out as a JavaScript framework AngularJS and now the current version is Angular 9 with a total of 6 major releases in between. This can cause confusion especially for beginners. 

Many a time, beginners struggle to understand the versioning. I have seen students learning a version of the framework, latest at the time, and by the time they finish their first project, a new major release is out. This causes trust issues. Developers, at times, feel that they must keep working on their apps and resolve version conflicts and compatibility issues. 

Decline in popularity 

With the advent of newer frameworks like VueJS and ReactJS, Angular has seen a downfall in its popularity. Just a few years ago, developers were mainly debating on whether they should be using Angular or React for their projects. But over the course of the last couple of years, we saw a growth of interest in a third player called VueJS or Vue.js.
 
While the job market in Angular continues to expand, it has been observed that the popularity of the framework has been declining. I believe that too many versions is one of the main issues that the framework needs to address. 

Lot of boilerplate code 

If you are building a simple app, there is a lot of boilerplate code that the application requires. Although with tools like StackBlitz, it has become easier to try code ideas and experiment without having to install anything on your computer, but if you decide to start developing an Angular app on your system, you need to install a bunch of things and the most simple “Hello World!” application will have a lot of code that you do not care about. 

What’s new in Angular 9? 

Let us take a closer look at what is in store for us in the Angular 9 version of the framework. We will delve into the latest version of Angular 10, released in June 2020, in a separate blog post. 

Step-by-step guide 

The official Angular website offers a step-by-step guide on how to upgrade your existing apps to the latest version. 

Step-by-step guide

Guide

Ivy, the next-gen compilation and rendering engine 

Ivy is the code name for Angular's next-generation compilation and rendering engine. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine. You can, however, disable Ivy if you still want to use View Engine for your app. It is a huge milestone for the framework. Ivy offers faster build times and small build sizes. It also offers a new change detection system.

The important point is that we don’t have to change how we write our applications. Ivy aims to be compatible with the existing applications. Ivy is going to be smaller, simpler, and faster as quoted by the Angular team.  

In the demo shown by Miško Hevery, the creator of the AngularJS framework,in ngConf 2018, the Hello World application was merely 3.2KB which is significantly small although 3.2KB is the result after minification + gzip.

Total bundle SizeTotal bundle Size

Ivy compiles one file at a time and therefore follows the locality principle. Ivy looks at a component's template when generating the compiled output. This process leads to faster compilation. Ivy makes sure that, if you are not using something in Angular, it does not get included. Since Ivy pipelining is simplified, templates will be part of the stack trace.  

No more cryptic error messages when something is broken in our template syntax as we will see the exact line number where the error is. 

The Ivy compiler has been designed to remove parts of Angular code that aren’t being used via a mechanism called tree-shaking and to generate less code for each Angular component. With these improvements, small apps and large apps can see the most dramatic size savings. 

Angular ahead-of-time (AOT)  

In Angular 9, AOT is enabled for Dev build as well. The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code.  

Compiling your application during the build process provides a faster rendering in the browser. AOT allows faster rendering of the application and also makes sure that there are a lot less asynchronous requests. According to the docs, AOT compilation with Ivy is faster and should be used by default. 

Lazy loading components 

Before Angular 9, we could only lazy load modules. Now, you can also lazy load components. It is a great way to shrink the size of your main bundle and boost the initial load of your application. Lazy loading of single components has not been possible so far. But things have changed with Ivy.  

Works with TypeScript 3.6 and 3.7 

The latest version of the TypeScript is 3.7 and Angular 9 is updated to work with TypeScript 3.6 and 3.7. Angular 9 supports usage of the same TypeScript Diagnostics format for the TypeScript Compiler diagnostics, which will generate more descriptive error messages. 

According to the official docs - “In TypeScript 3.7, when opening a project with dependencies, TypeScript will automatically use the source . ts / . tsx files instead. This means projects using project references will now see an improved editing experience where semantic operations are up-to-date and “just work”. 

SupportscCSS variables or custom properties 

Angular 9 supports CSS variables or custom properties. CSS variables or custom properties allowsdevelopers to define their own variables for CSS values that can be shared between components and style rules.  

CSS custom properties or CSS variables allow the CSS property values to be changed at runtime. The possibility that the CSS custom properties can be updated during runtimeopens the opportunity to easily create themes for newer Angular application.  

Angular:Quick tips and facts 

Angular is a framework used for front-end development. This involves the client-side of the application and has little to do with the back end. 

  1. Angular is best utilized for completing advanced, large-scale projects under the direction of a seasoned developer. 
  2. Angular is created for enterprise-scale applications. 
  3. Angular elements can be added to projects that were built using a different platform, such as React or Polymer. 
  4. Angular is supported by Google. 
  5. This program is not up to par with SEO best practices, so if your primary focus is search engine optimization, opt for a different platform. 
  6. Angular is a JavaScript framework—not a JS Library.
  7. Angular ranked second in “most used technology” in the Stack Overflow Survey of 2018.  

How to get started with Angular?

Are you ready to take on the best and become a master of the Angular framework? Check out the Angular Training and Certification which comes with instructor-led live training and real-life project experience.  

This training will help you understand Angular in-depth and help you achieve mastery over the subject. 

Master Angular programming with our in-depth online courses. Explore them now!

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

Trending blog posts

Suggested Blogs

Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.For the email provider, we are going to use Sendinblue. Prerequisites Node.js (>v6.0.0 for nodemailer module) Code Editor (For Ex. VS Code, Atom) An account in SendinblueStart by creating a free account in Sendinblue. A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. An introduction to Nodemailer Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. Highlights of Nodemailer It is a single module with zero dependencies  It supports HTML Content  Allows you to easily add attachments to messages Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. OAuth2 authenticationGetting Started For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. Create a new directory nodemailer-example.  Open the terminal or cmd inside the directory and run  $ npminit --yes It will initialize a new npm package. Install dependencies Following different npm packages, we are going to use in this project. nodemailer – To send the mail express – To create APIs cors – To resolve the cross originresource sharing body-parser – To extract the body from the API request dotenv – To access the environment variables $ npm install --save nodemailer express cors body-parser dotenv This command will install all the dependencies. Now, we can start the coding. Project Structure Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  nodemailer-example    |- routes      |- mail-api.js    |- src      |- send-mail.js    |- template      |- mail.html    |- .env    |- index.js Sendinmail Setup Login to your Sendinmail account. From the top-left menu, select SMTP & API. Select the SMTP tab. Click on Create a new SMTP key. Copy the key at some safe place.  You can deactivate the SMTP key anytime. Now, open the .env file and create 2 key-value pair. USER=YOUREMAILADDRESS  PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx USER: The email address using which you created the sendinmail account. PASS:SMTP Key By using .env file we are not exposing the credentials to the web.  Using environment variables in the project is an industrial standard.  Source Code Open the send-mail.js in the editor. Copy and paste the below code in it."use strict";  require("dotenv").config();  constnodemailer = require("nodemailer");  /**   * sendEmail   * @param{Object}mailObj - Email information   * @param{String}from- Email address of the sender   * @param{Array}to- Array of recipients email address   * @param{String}subject - Subject of the email   * @param{String}text - Email body   */  constsendEmail = async (mailObj) => {  const{ from, to, subject, text } = mailObj;  try {  // Create a transporter  lettransporter = nodemailer.createTransport({  host:"smtp-relay.sendinblue.com",  port:587,  auth: {  user:process.env.USER,  pass:process.env.PASS,        },      });  // send mail with defined transport object  letinfo = awaittransporter.sendMail({  from:from, // sender address  to:to, // list of receivers  subject:subject, // subject line  text:text, // plain text body      });  console.log(`Message sent: ${info.messageId}`);  return`Message sent: ${info.messageId}`;    } catch (error) {  console.error(error);  thrownewError(  `Something went wrong in the sendmail method. Error: ${error.message}`      );    }  };  module.exports = sendEmail; Code Walk Through In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. The sendEmailfunction accepts an object. This object has from, to, subject, text fields. Please note that, from and USER must be same. The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object.  let transporter = nodemailer.createTransport({       host: "smtp-relay.sendinblue.com",       port: 587,       auth: {         user: process.env.USER,         pass: process.env.PASS,       },     });Open SMTP tab in your sendinmail account and cross check the host and port.In the auth object, we are passing the user and password from the environment variable.Send the mail using sendMail method.// send mail with defined transport object     let info = await transporter.sendMail({       from: from, // sender address       to: to, // list of receivers       subject: subject, // Subject line       text: text, // plain text body     });It returns a Promise of Send Message Info. In the end, it is returning the message id.  Express Route The sendEmail method is ready.  Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. Open the mail-api.js in the code editor and paste the below code. constexpress = require("express");  constrouter = express.Router();  constsendMailMethod = require("../src/send-mail");  // Post request to send an email  router.post("/sendmail", async (req, res) => {  try {  constresult = awaitsendMailMethod(req.body);  // send the response  res.json({  status:true,  payload:result          });      } catch (error) {  console.error(error.message);  res.json({  status:false,  payload:"Something went wrong in Sendmail Route."          })      }  }) module.exports = router; The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  In the end, we are exporting the router. Now, this can be used in the server side. Express Server Now, it’s time to create a server and expose the routes on it. Open the index.js and paste the below code in it. "use strict";  constexpress = require("express");  constbodyParser = require("body-parser");  constcors = require("cors");  constapp = express();  constmailAPI = require("./routes/mail-api.js");  // Express body parser  app.use(cors());  app.use(bodyParser.json());  app.use(  bodyParser.urlencoded({  limit:"50mb",  extended:false,  parameterLimit:50000    })  );  // use the routes specified in route folder  app.use("/api/v1", mailAPI);  constport = process.env.PORT || 4444;  //listen to the server  app.listen(port, function () {  console.log(`listening to the port ${port} .....`);  }); The route is available on /api/v1/sendmail. Run the server. $ node index.js  listening to the port 4444 ..... Send an Email using API There are couple of methods to test the API. Using the Postmanor using the Curl command. Using Postman Install Postman on your machine if it is not installed. Create a POST request. URL: http://localhost:4444/api/v1/sendmail Content Type: JSON – Body tab > select JSON from dropdown Request Body:  {  "from": "hello@schadokar.dev",  "to": ["shubham@schadokar.dev"],  "subject": "Mail from Nodemailer",  "text": "Sending an email using nodemailer package."  } Hit Send. Make sure the server is running. On Success, the response returns the message id. Now, check your mailbox. If you are unable to find the mail in your Inbox, check the promotional mail folder. Using Curl CommandOpen the terminal or cmd.In the below curl command, change the parameters and enter.curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'In this example, we have sent a simple text message to the recipient.  Nodemailer also gives you an option to send the message in HTML format. Mail template Open the mail.html in the code editor and paste the below code. 
6792
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email ... Read More

Full Stack Development – the Hottest Developer Skill for the Digital Age

With over 1.7 billion websites worldwide and 4.54 billion people using the internet actively, the need for heightened customer experience is on the rise. This is one of the major reasons why professionals who are adept at handling both the client-side and server-side interfaces of an application/website have become more important than ever. It has been estimated that by the next decade, there will be 300,000 new developer jobs in US. The Full Stack developer role is the No.1 position to be filled in 2020 according to 38% of hiring managers. This is closely followed by the role of a back-end developer.Handsome pay packagesThe average annual salary for a full-stack developer is about $110,737 per annum. Even beginners are offered about $58,000 per year and on the other hand, experienced professionals would earn up to $188,253 per year.These professionals are paid handsomely because enterprises are aware that a full stack developer does the job of two professionals (back-end and front-end developer).Plenty of growth opportunitiesAs per reports by The United States Bureau of Labor Statistics, full-stack development job opportunities will increase from 135,000 to 853,000 by the year 2024. This is quite promising for aspiring full stack developers as an ocean of opportunities will be available for them in both startups as well as in multi-national organizations.Skills to become a Full Stack developerBecoming a full-fledged full stack developer is not child’s play. It takes a wide range of skills to become a good full stack developer. Below are the mandatory skills:Front-end skills: They should be well-versed with basic front-end technologies like HTML5, CSS3, and JavaScript. They should also be comfortable working with front-end frameworks or third-party libraries such as JQuery, SASS, and AngularJS.Programming languages: They should be aces in at least one server-side coding language like Java, Python, Ruby or .Net.Databases: They should be efficient at handling data from databases like MySQL, MongoDB, Redis, Oracle and SQLServer.Version control systems (VCS): Full stack developers must be aware of Git so that they can make appropriate changes to the codebase.Basic design skills: Awareness about the basic prototype design and UI/UX design is essential to become a successful full stack developer.Server and API: They should have adequate exposure to Apache or Linux servers as well as web services.The way forward for Full Stack developersThe growing demand for full-stack developers is due to the ample benefits they offer to organizations. With technology evolving at a rapid pace, foresighted companies will keep adding them to their workforces. Full stack development became the No.1 developer skill because these developers are trained to multi-task various technologies and products. For aspiring full stack developers out there, now is the best time to make the most of these opportunities.Real products require real challenges. Check out our live online workshops and build your portfolio of projects.
4858
Full Stack Development – the Hottest Develop...

With over 1.7 billion websites worldwide and 4.54 ... Read More

What are React Component Lifecycle Methods

React is the most popular JavaScript library used to create interactive UI for web applications. It is a component-based library where different parts of a webpage can be encapsulated by components which are quite easy to create, manage and update. React allows us to create Single Page Applications which maintain the state of individual components on an app without having to reload it.  What are React Components? Developers who are new to JavaScript libraries and frameworks like React and Angular might ask the question, “What is a component?” Well, in very simple words, a component is a unit of code which includes JavaScript and HTML to build a part of a web page. It acts like a custom HTML element. It is reusable and can be as complex as you want it to be. For example, imagine that you are creating a very basic application with header, footer, and body. The header can be a component; the footer can be another component and the body can be yet another one or even might consist of multiple components.One of the most useful characteristics of React is its ability to integrate reusable components in a project. Reusability is the characteristic of a component which allows it to be used again, thereby reducing the amount of code a developer has to write. In our example here, the header can be a reusable component and can be used on all the pages of the application, which makes it easy to maintain and update. What does a component look like? Here is a simple example of a react component which contains a simple form. This is a class-based component. React also supports function-based components. As you can see in the code below, App is a user-defined class which inherit from React’s Component class and it has a render method which returns HTML code. As the name suggests, the render method returns and renders HTML to our browser. Every component has to return HTML which is rendered to the user’s browser by render method.import React, { Component } from 'react';  class App extends Component {    handleChange(event) {      this.setState({value: event.target.value});    }    render() {      return (                              Username:                                            Password:                                              );    }  }    export default App; In the above example, we have created a login form where there are 2 input boxes for the user to enter their username and password and then submit the form. We have assigned an event handler to form which will handle the login event in component.We have exported our component (using export default App) so that it can be rendered inside other components.This is a very basic example of component, but this can be as complex as you want it to be. But it is always advised to make your component independent and it should represent only a part of your page which can be reusable as well. It can return complex HTML included with JavaScript to handle complex features in your application.Component as a class React allows us to create component in the form of class as well as functions. While creating component as class you need to define a class which extends React.Component class. Component class has many features which the deriving class can use to maintain the state throughout the lifecycle. In case you want to have more custom features, you can create your own base component class which derives from Component class, and then your component classes can derive from your base component class. What do we mean by Component Lifecycle?Lifecycle of a component is the set of different stages (also known as lifecycle hooks) a component goes through while it is active. Stages could be when a component is created or when any changes are made to the component and many others. There are different methods executed by React at different points of time between when a component is created and at the end when it is destroyed and not in use. One such hook or method we have already seen in the code above, which is render(), and it is executed by React to render the component. We can override these methods and perform certain tasks in those methods, but every lifecycle serves a different purpose and it can be a nightmare if we ask them to do something that they aren’t supposed to or are not very good at. As a developer we should be aware of what those different stages are, what happens in those stages, in what order they execute and how we can make the best use of it. Understanding the lifecycle of components also helps us predict behavior of a component at different stages, which makes it easier to work with them. Managing a large set of components in an application can get you in trouble if you do not know how they work behind the scenes.Props and State Before we start with lifecycle hooks, lets understand what props and state are as they are most commonly used properties in component classes. Props It is a keyword which means properties. Props are used by callers of components to pass properties to the called component in a uni-directional flow. For example, if Parent component renders child component, it can define props and pass them to the child component which is then available and accessible by this.props. Another thing to note here is that props is a ready-only attribute which means data which is passed by parent should not be changed by client components. State State is a plan JavaScript object which defines the current state of any component. It is user defined and can be changed by lifecycle hooks. Ideally state should contain only data which is going to be rendered on DOM. State has getter and setter methods this.getState() and this.setState() which as the names suggest are used to access and update State. It is good practice to use setState method to update State and treat State as an immutable JavaScript object.Since there are many lifecycle hooks a component goes through, it would easier to understand if we start with the hooks which are executed when a component is created.Lifecycle hooks while Mounting [These lifecycle hooks are executed in order as listed, when a component is created]constructor(props) This is not a component lifecycle hook, but it is important to mention here and to be aware that Constructor is executed before it is mounted. Constructor receives props(properties of a component) as an argument which then can be passed to base class using super keyword if we define the constructor.  It is not mandatory to define constructor in component class, but if you do to perform any logic, then you need to call base constructor using super keyword.  Mainly constructors are used: To Setup local state of component with this.state To bind event handler methods. This is what a simple constructor would look like.import React, { Component } from 'react';  class App extends Component {    constructor(props) {      super(props);      this.state = { value: 0 };      this.handleClick = this.handleClick.bind(this);    }  } this.state should be called only inside constructor, to update the state in other methods use this.setState() method.  If constructor is required to do any heavy tasks, it will impact the performance of component, and you should be aware of this fact.  getDerivedStateFromProps(props, state) After constructor, this lifecycle hook is called before render method is executed. It is called while mounting as well as whenever props have changed. This is not very commonly used, only in cases where props can change, and you need to update state of the component. This is the only use case where you should implement this lifecycle hook.This method is executed on every render and cannot access component instance.import React, { Component } from 'react';  class App extends Component {    getDerivedStateFromProps(props, state) {      if (props.value !== state.prevValue) {        return {          prevValue: props.value        };      }      return null;    }    }render() This is the method which is required to be implemented in component class. It can access props and state. This is where you can write your html and jsx code. You can also render child components in this method which will then be rendered as well. Before completing the lifecycle of parent, lifecycle of all child components will be finished. All this html and jsx is then converted to pure html and outputs in DOM. JSX is a JavaScript extension which creates React elements. It looks more like template language but it is empowered by JavaScript which allows it to do a lot more. It can embed expressions . JSX has different set of attributes than what we have in html. For example, while creating html using JSX you need to use attribute “className” instead of class. This is what a typical render method looks like:import React, { Component } from 'react';   class App extends Component {   render() {         return (        Click to go Home { this.state.home }       Go to Home         );   } } Alternatively you can also use React.createElement() method to create html using JSX.const element = React.createElement(       'h1',       {className: 'hello'},       'Hello, world!'     );componentDidMount() As the name suggests, componentDidMount() is invoked after the component is mounted, which means html has been added to DOM tree. It is a very commonly used lifecycle hook, as it allows you to do a lot of things including causing side-effects, setting up any subscriptions, or loading data from external endpoints. If you setup any subscription using this method, make sure to unsubscribe them in componentWillUnmount() lifecycle hook. You shouldn’t update state in this method using this.State() as it may cause performance issues. For assigning initial state you should use constructor(). import React, { Component } from 'react';  class App extends Component {    componentDidMount(){    // Component is rendered and now external calls can be made.      this.getDataAfterTimeOut();    }    getDataAfterTimeOut(){      setTimeout(() => {        this.setState({          data: 'Data is fetched'        })      }, 1000)    }  } Lifecycle hooks while Updating [Next set of lifecycle hooks are executed while a component is updating which can be caused by changes to props(properties) or state of component. These are invoked in order as listed below.] getDerivedStateFromProps(props, state) We have already talked about this. This is invoked every time a component is changed or updated. Any changes in properties or state which causes the component to be changed will invoke this method. shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate() is invoked before rendering (not on initial rendering) but only when props or state has been changed. Even though it is not recommended you can use this lifecycle hook to control the re-rendering. This can lead to performance issues as well as bugs, so be careful while doing that.  In this method nextProps can be compared with this.props and nextState can be compared with this.state. This method can return true or false depending on whether you want to continue rendering by skipping the next lifecycle hooks. In either case it can’t prevent re-rendering of child components. Note that this method defaults to true which will not skip rendering and next lifecycle hooks and continue with execution. import React, { Component } from 'react';  class App extends Component {    shouldComponentUpdate(nextProps, nextState) {  // This value will determine if lifecycle execution is to be skipped or continued.      return nextProps.value != this.props.value;    }  } render() After shouldComponentUpdate lifecycle hook render is called, which we have already talked about, it prepares html and jsx code which then outputs to DOM. getSnapshotBeforeUpdate() getSnapshotBeforeUpdate() is invoked right before the recent changes are added to DOM. This lifecycle hook gives us an opportunity to capture any details we need from the DOM before it is updated with new content. For example, if you want to know the scrolling position of the user, which should be restored after the DOM has changed. Use cases for this lifecycle, while rare, can be of great value at times. The snapshot value which is captured and returned by this hook is passed as a parameter to another lifecycle hook componentDidUpdate() which we will talk about next. import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate (prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      if (this.state.value != prevState.value) {        return table.scrollHeight - table.scrollTop      }      return null    }  }componentDIdUpdate(prevProps, prevState, snapshot) componentDidUpdate is invoked when DOM is updated. It is only called on update, not on initial rendering. You can use this method to make data requests after checking if props have changed. You can also call setSatate() in this method, but make sure to wrap that in a condition else it will cause an infinite loop forcing re-rendering and affecting performance issues. Also it should be noted that value for snapshot will only be available if you have implemented getSnapshotBeforeUpdate() in your component; else value for snapshot will be undefined. Here is an example of componentDidUpdate. This is a very basic example where we have captured snapshot by implementing get Snapshot Before Update lifecycle hook. After that componentDidUpdate is invoked and content is overwritten with new dataimport React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } UnMounting [This is where lifecycle of a component ends when component is destroyed and removed from DOM. While Unmounting React gives us an opportunity to do something before component is destroyed, it can include clearing objects which have occupied memory to avoid memory leaks.] componentWillUnMount() componentWIllUnMount() is executed right after component is unmounted which means it is removed from DOM and destroyed. But before it is removed and destroyed, React gives us an opportunity to perform any cleanup we want to. For example, you might have setup subscriptions initially in componentDidMount() which you should unsubscribe when component is destroyed to avoid memory leaks in your application. You can also remove event listeners which were subscribed before. In this lifecycle hooks you should not update state of your component because component is not going to re-render now.import React, { Component } from 'react';  class App extends Component {    componentWillUnmount() {  // Component will be removed from DOM now.        // Unscubscribe subscriptions and events here.  document.removeEventListener("click", this.handleSubmit);    }  }Conclusion In this article we talked about React, its components and its different lifecycles. It is very crucial to understand the different opportunities that React provides through these lifecycle methods. There are many rules we need to follow while working with these hooks. Making them do something they can’t handle can cause performance issues or even infinite loops at times.  These lifecycle hooks work with props and state which are the most used properties of component class. Changes in state and props trigger different lifecycle hooks and even re-render the dom which is something you should be aware of. These lifecycle hooks are provided to intercept the different stages a component goes through and make the best use of it, but without understanding how they work it can break your application by causing performance issues or memory leaks. Hope this has been helpful. 
9272
What are React Component Lifecycle Methods

React is the most popular JavaScript library us... Read More