Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular Best Practices and Tips for Developing Application

Angular has been the most famous javascript framework among the developer community. It’s an MVC framework which provides pre-built components for developing the software application.

Angular(2+) is based on Typescript , which is a superset of JavaScript. It comes with its most important advantage of static type checking that provides compile-time checking for any variable declarations and definitions.

This blog is based around some best practices for Angular which I figured out while developing applications. There are also some bonus tips which I believe would help you with Angular development.

So, let’s see the best practices for Angular one-by-one:

Follow the component based approach

Angular comes with the component-based paradigm which is also one of its best practices. It helps in maintaining modular and readable code.

While developing an angular code, if you think that something can be used multiple times as an independent piece of code, make it a component. A very basic example can be a simple dropdown which shows a list of options. The drop-down can act as an independent component with its own methods and template.

Few more examples could be – breadcrumbs for navigating throughout our web application, a simple alert box showing error/success messages or a loader. We tend to ignore these while thinking of modular approach but all these above examples can be thought of as independent components which can be reused over and over again.

Avoid using one huge global CSS

Angular’s current structure includes individual folder for every component. This folder includes-

  • .ts file for component logic
  • .html file
  • .css file for the component

So, keeping all of your CSS in one common CSS file would not only make your code less readable, it would make it less maintainable.

The best approach to style your components is to separate the global CSS with the local CSS (here local CSS refers to the component CSS). You should write your CSS in global CSS only when the CSS is written for the entire application and then if you need to style your component specific to a certain page, you can surely write in the local CSS.

Component structure of Angular

Use CSS preprocessors for faster development

We can also use CSS preprocessors like SCSS/SASS for our Angular projects and I prefer them instead of writing plain CSS as they provide a lot of advantages over writing plain CSS. To mention one, the use of partials so that you can also separate your styles into multiple files for maintainability. If you guys want to know about partials, I would suggest you to go through this link.

You can divide your styling into multiple SCSS files just as we divide our application into multiple components. SCSS/SASS helps in writing smaller code which would ultimately get converted into CSS. So, why not save time and use it to our advantage.

Save your time by using build tools

Tools like angular-cli have come up as a lifesaver for angular developers. It’s basically a boilerplate for an Angular application which helps in quickly setting up the angular application for your new project. It comes with all dependencies required for building your application and also has an inbuilt webpack which helps in bundling all your code and assets. Angular CLI helps to increase developers productivity through scaffolding by creating a component file, template file, stylesheet file etc. It comes with few basic commands which help in faster development like:-

  • ng g component my-new-component – it will create a new component with the name my-new-component.
  • ng g service my-new-service – it will create a new service with the name my-new-service.
  • ng g module my-module  – it will create a new module. A module is basically a collection of components which help to serve or attain a particular functionality.

Use ES6 paradigm and approach

Though right now ES-8 is the current drafted version for ECMAScript but ES-6 came up with its own new features that are still widely used by developer community as they produce the same results with fewer lines of code and for best practices, every developer should know how to use them.

  • Arrow Function – In javascript, we use this keyword to refer to the Current Execution Context. Previously, when we had to write javascript functions, this keyword would refer to the function context and we had to use a temporary variable to store the current execution context, so that we never lose it but with the arrow functions, the current execution context is never lost. For e.g., we could use an arrow function like this;

// ES5

var sum = function(x, y) { return x + y };

// ES6 (arrow function)

var sum = (x, y) => { return x + y };

Now, see the ES6 arrow function is just so compact and easy to understand and we can easily use this keyword inside this function to refer to the current execution context.

  • Template Literals – Template literals have come up with how we deal with printing strings having dynamic content.

For example, without template literals if we had to print a hello and goodbye message to a person, we would write something like :

const name = ‘AMAL’

console.log(‘Hello ’ + name +’ !’);

console.log(‘Goodbye ‘ + name + ‘ !’);

Now using template literals, it would be something like this:

const name = ‘AMAL’

console.log(`Hello ${name} !`);

console.log(`Goodbye  ${name} !`);

Now, who wouldn’t like to use the second syntax as it’s really easy to use and we don’t have to care about putting the spaces at right places so that the formatted output is correct.

Apart from these, const and let keywords came up as a replacement for global var variable so as to enable effective scoping of variables.

For a detailed overview of ES6 features, I would recommend having a glance over this.

Use Lazy Loading wherever possible

Lazy loading is based around loading modules only when you want them to show.

We know about Angular’s modular architecture where a code is divided into modules with each module having its own components.

These components are basically views which might have some dynamic data. These components are rendered with the help of angular routing.

Lazy loading is one of the best things that angular framework comes with.

It’s based around one principle – ‘load/use it when you need it’. Oh, yeah what a lame
explanation I’ve given. There is a routing.ts file in every module which defines a URL for rendering each and every component.

Now when it comes to implementing lazy loading technique, what we do is we define a routing file for each and every module and we import each module only when the URL changes and it corresponds to rendering a component defined in the routing file of that module.

This technique requires a bit of patience to learn but take my words, it’s worth implementing. I can tell you with my personal experience; we reduced the loading time of our website by 3-5 seconds by implementing lazy loading.

Previously, we imported the whole bundle each and every time the user hit our website URL making our site slow while rendering. Then after implementing lazy loading, we only imported the module containing component required to render our index page and we just loaded other modules only based on what URL the user is switching to.

The Angular docs surely cover the lazy loading technique and it’s worth reading. You can check this link to learn more about it.

Follow DRY principle, extensively use services and directives

Services

DRY – This keyword is very famous in the developer community and it just stands for Don’t Repeat Yourself. So, when writing any code- be it Angular or any language- if you feel that you are basically writing or repeating the same code in every component, then you must pause then and there and rethink whether the code can be placed at a suitable place and can be shared by every component.

For example, if you want to call an API that updates user data, don’t call it in every component. What I would do it, I would rather make a service for it in the .service.ts file and would call that function whenever I need any component.

Also, it serves the purpose of using services in angular. Services help us in saving and fetching data and also help us write common functions which could be used by multiple components.

An example of a service

Directives

Now switching over to directives. A directive is a piece of code which is used to perform a specific task. Directives are of 3 types in Angular – component, structure, attribute.

  • Components are as we all know templates with logic to handle data.
  • Structure directives modify DOM by adding or removing an element.
  • Attribute directives change appearance or behavior of an element.

Once, I was wondering to restrict input elements to accept only numbers when a user types in for a phone number field which shouldn’t accept alphabets. For this, I built an only number directive which would only allow input elements to accept numbers through the keycode. So just by using this directive as an attribute on an HTML input element, I can modify/change its behavior.

Conclusion

Following best practice is never a compulsion. There are many ways of doing things and you may choose any path. However, using best practices mean that you are following a method or a technique which is tried and tested through experiments and has proved to be effective to attain desired results.

I found these practices to be extremely useful while coding. I hope you get to use them and write better code. Thank you for reading the blog. Please drop in your comments if you have any questions.



This post first appeared on C.R.A.P. Design Principles To Improve Visual Appeal, please read the originial post: here

Share the post

Angular Best Practices and Tips for Developing Application

×

Subscribe to C.r.a.p. Design Principles To Improve Visual Appeal

Get updates delivered right to your inbox!

Thank you for your subscription

×