Introduction to Angular Best Practices
By: Serdar Sayın
Tags: Typescript, Angular, Best Practices, JavaScript, Clean Code

1. Template Conditions

If you even come across an Angular codebase, you’ll see that template conditions are the backbone of the template. This tip is not for improving the performance or functionality. This is all about developer experience.

You can see the difference at a glance. This may seem trivial at first but when the conditions get complicated it’s better to encapsulate them into a variable with meaningful naming. Sometimes you have no choice but to define in the template (Loops), writing meaningful comments would suffice in that case. You got the idea 🚀

2. ESNext Features

Writing better Javascript code is a requirement for better Angular applications. ESNext features are a topic on their own but I’m going to mention features that I use every day. This is something you need to keep yourself up to date because it changes periodically. These are just the tip of the iceberg. I urge you to read more about ESNext features.

Spread Operator

The spread operator is one of the most versatile features in Javascript. You can accomplish so many things. Here are some.

The last one is a real-life example. Basically if hobbies is present assign hobbies , if hobbies is falsy don’t even set as hobbies: null instead, leave that property empty.

The syntax is debatable. It can be simplified or you can still achieve the same result with alternative methods. I can assure you it will be messier.

As a result, the spread operator is a powerful and nice tool to have in your arsenal.

For more information

Arrow Functions

If you ever had to write a code like this var self = this; . This one’s for you.

Arrow function is a concise, simplified version of the traditional function. There are some things it can and can’t. For instance, the arrow function doesn’t have a separate scope so it shares the parent’s scope unlike the traditional one. Tackling data fetching and Observables is way easier with arrow functions.

Arrow function vs Normal function

For more information

3. Short-Circuiting in Javascript

From my experience, this is one of the most overlooked features of the language. Not every language supports this but luckily JS does.

To assign a value to result , the engine seeks out a shortcut. If the condition is met before reaching the end, it short-circuits and moves onto the next line.

In the example, only checking the condition of variable “e” is enough if you order correctly. By utilizing this feature you can prevent loading states/unnecessary API calls and you can even reduce initial load latencies.

Check out this article to see how important is short-circuiting 😛

4. ngFor with trackBy 🔮

Most of the time, you can foresee the future of the lifecycle of an application. You may assume specific changes in your template or simply you may don’t want your template to react to every little change. Wouldn’t be nice if Angular renders only when we want to? That’s where trackBy comes into play. trackBy is just a function to compare data with its previous state. If it’s different rerender if it’s not no action.

Let’s take a quick look at this example. There are two versions one with trackBy and the other is without.

If there is no trackBy, every time data changes every element inside of that loop is going to rerender 😒

If we track the change only we care, Angular engine wouldn’t rerender unnecessarily.

ngFor without trackBy

ngFor with trackBy

For the sake of this article, I only recorded the DOM so we can see the difference. For both cases, I’m clicking the same button relentlessly. Simple ngFor rerenders every time button is clicked, However, on the second one trackBy function looks for change and It only renders if there’s a difference after the button is clicked. Just be careful, It’s not a silver bullet. Sometimes you don’t want trackBy . (When you want to display every little detail 🤔)

Check it out.

5. Virtual Scrolling with Angular CDK

I can’t stress enough how important this one is. Especially if you have to develop a page with too much scrolling. Like the previous tip, this is also about performance. Angular CDK’s examples are more than enough to justify the needs of this feature.

Angular material docs also simplify the process into one sentence.

Virtual scrolling enables a performant way to simulate all items being rendered by making the height of the container element the same as the height of total number of elements to be rendered, and then only rendering the items in view

Here is a list of the most obvious aspects of virtual scrolling.

It doesn’t render every possibility at once. It only renders the ones that are visible to the user. It utilizes caching and uses the same template when it’s possible. In basic terms, it recycles the template therefore more performant loops. 💪

Check out here for more information. I also want to encourage you to play with examples and see the difference in the DOM.

6. Pipes in Angular

Sometimes we — Frontend Developers — forget the fact that Angular takes care of so many things for us. Sometimes it’s overwhelming, most of the time it’s cool

This is a cool one. 🚀

When you import a common module, not only ngIf comes with it. Some super-useful pipes are built-in. I’m going to focus on the two most useful ones.

CurrencyPipe

At some point in my career, I had to work with dozens of currencies and almost each of them had different requirements. Too many commas, zeros it was overwhelming. Currency pipe was handy, and I took a step further and extended CurrencyPipe which was pretty easy.

DatePipe

The same thing applies to DatePipe. Don’t take these pipes for granted and utilize them as much as you can 💪

Not only Angular’s own pipes are useful there are some fantastic ones out there. Here is one

7. Don’t forget to unsubscribe streams.

It feels really straightforward to subscribe to a stream. Do you feel the same thing about unsubscription? If you are lucky, you may not even realize that you need to unsubscribe. It’s that subtle.

If I try to explain every bit of this concept I would need to write another article. Let’s make it simple. If you don’t want memory leaks and performance issues, you have to unsubscribe from streams (Observables, events, etc.).

There are several ways of unsubscribing here are some.

Use async pipe. Angular takes care of the unsubscription when the template is destroyed. You can unsubscribe from the source on ngOnDestroy hook. However, you should be careful about this one. You may still want that Subscription to exist. If you want to take the specified number of value from the source. You may want to consider RxJS operators like take, takeLast,takeUntil, first. These operators don’t require unsubscription.

8. RxJS operators

Nice transition eh 😜

Angular ecosystem is super-rich when it comes to reactive programming. NgRx and Akita are just from the top of my head. I’m not even mentioning how HttpClient works in Angular.

The funny thing is if you invest in yourself to learn RxJS, all of these concepts apply to almost any other language. Checkout RxSwift and RxJava.

Here is my take on this. Invest in learning RxJS. You won’t regret it.

If no one said it already.

Codebases, languages change, design patterns don’t.

Here are some great resources would help your understanding to level up.

https://www.learnrxjs.io/

9. Dumb-smart components

Drawing on dumb-smart component

The title may not sound delicate enough. In essence, the idea is like this. You have a smart one and several dumb ones for that specific feature/page. The smart component takes care of more “logical” stuff and passes enough data to dumb components to present.

For example, if the Sidebar component emits an event and this event has to trigger another component — you guessed it right — the smart component takes care of it.

I first learned this concept from Dan Abramov. Even though he sort of changed his mind in this concept especially for React development, I still believe it’s a good practice to separate your components in this fashion.

10. Using Augury

Augury is sort of an equivalent of React/Vue dev tools. I didn’t benefit too much while I develop Angular apps but when you want to see an overview of your application from a broader perspective it’s quite useful. Especially if you are on a relatively bigger project.

Check it out.

11. [hidden] vs ngIf

The difference between ‘hidden’ and ‘ngIf’ is quite subtle yet super powerful when the time comes. Imagine you have a component with a huge template. However, initially, the user doesn’t want to see this feature.

I do smell performance.🤔

If you choose hidden, the component won’t be rendered in the DOM but if you inspect you’ll see that everything is loaded but marked hidden.

On the other hand, If you choose ngIf, it will comment out the data if the expression is false. This will reduce the initial load but components need relapse for loading.

Basically, it’s a trade-off.

hidden vs ngIf on DOM

Here is a quick example you can see the same results.

12. Absolute path with tsconfig.json

This one is gold ✨

I’m sure you encounter import statements like this. It just doesn’t look pleasing and maintainable.

import {GrazieModule} from './../../app/shared/component/grazie.module

🤮

tsconfig.json file

Luckily Typescript takes care of this mess if you make enough adjustment. In your tsconfig.json file, you can create absolute paths. Only lines that matters are from line 17 to line 32. You are sort of creating a shortcut for that path. Now you can rephrase it as following.

import {GrazieModule} from '@shared/component/grazie.module'

❄️ VSCode is really helpful if you make these adjustments. It suggests you use shortcuts instead of relative import.

13. Attribute/class/style binding

Using binding may not be on top of your head. Sometimes it might be tempting to go for ngIf rather than adding a class binding. However, It’s more performant and better DX overall.

👾 Using attribute binding with BEM is delightful.

Let’s take a look at this comparison.

Comparison of ngIf and attribute binding in a template

It might seem trivial but the difference is too big to ignore 🤷‍♂️

Yaaay! 🎉

I hope you learned some new stuff. We just scratched the surface. There are tons of things that I didn’t mention because it’s an introduction. Check out this awesome article and check out the best practices section of Angular docs.

If you have any questions or any remark don’t hesitate to contact me ✌️

Good morning, and in case I don’t see ya: Good afternoon, good evening, and good night! 👋

Resources