Top 7 Angular Best Practices to Organize Your Angular App SAARE JAHAAN SE ACHHA HINDSUTAN HUMARA
www.bacancytechnology.com
Angular is a JavaScript framework widely used to make web apps, truly native apps and especially SPAs, efficiently. Angular has been designed in a way to overcome the limitations of other frameworks. With its dynamic features, you can create the best web apps with optimized speed and performance. The interactive tools offered by the Angular framework outdoes the features of other existing frameworks. Once you are developing your project using Angular, there’s no need to rely on other third-party libraries. Despite all the compelling features offered by Angular, if you overlook your coding practices for the Angular code, there are chances of facing performance issues.
Maintaining your code is very important, not only for Angular but any other framework, because it directly affects the output, and you surely don’t want a clumsy web app. In this blog – we will discuss Angular best practices to improve your Angular app performance instantly. Get knowledgeable on how to refine your Angular code with a clean code checklist in Angular.
Angular Best Practices to Improve Your Angular App Performance
1. Make Use of trackBy Whenever thereâ&#x20AC;&#x2122;s a need to generate different templates for each item from the collection, we use the built-in Angular directive â&#x20AC;&#x201C; ngFor. < ul > < li *ngFor="let item of items;">{{item.id}}< /li > < /ul >
Now, letâ&#x20AC;&#x2122;s see what the problem with ngFor is. Suppose we need to change the iterative data due to some requirements. In that case, it will cause the problem as Angular doesnâ&#x20AC;&#x2122;t keep any record of the data being iterated and is unaware of the data being added or removed. For implementing this, Angular releases all the DOM elements related to the collection and adds them again. And we all know how expensive DOM manipulations can be when dealing with a massive collection of data. To avoid this costly manipulation, we can use trackBy. The use of trackBy is considered one of the optimum techniques to be followed. It gives a unique identifier to each item of the collections, and thus the render process of the whole DOM can be avoided.
@Component({ selector: 'demo-app', template: ` < ul > < li *ngFor="let item of items;trackBy: trackByFunc">{{item.id}}< /li > < /ul > < button (click)="getAllItems()">Click to Refresh< /button > `, }) export class DemoApp { constructor() { this.items = [{id: 10}, {id: 20}, {id: 30}]; } getAllItems() { this.items = this.getAllItemsFromServer(); }
getAllItemsFromServer() { return [{id: 10}, {id: 20}, {id: 30}, {id: 40}]; } trackByFunc(i, item) { return item.id; // or i } }
2. Try Avoiding the Use of Logic in the Component Itâ&#x20AC;&#x2122;s quite necessary but considered the best way to keep your component separate from your logic. I have seen many developers mixing the components and business logic; making it too complicated and messy to understand. And thatâ&#x20AC;&#x2122;s why it is advisable to use the logic in a separate service.
Here are the reasons for avoiding the use of logic in the Angular coding standards â&#x20AC;&#x201C; Testing user interface and components is treated differently and is quite tricky compared to logic testing. And thatâ&#x20AC;&#x2122;s why you should have separate services for component and business logic. Different services for business logic improves code quality and reusability. When you have your logic in your separate service, you can use that service in multiple components. And this way, the code coverage Angular decreases and eventually the build size too. You can reuse the code to write less code.
It indeed enhances the code review, readability, neatness of the code, and performance of the high-scale application.
3. Use of Lazy Loading The use of Lazy Loading can help you increase the performance and productivity of your application. Lazy Loading is a builtin feature that allows Javascript to load the component asynchronously whenever that particular route hits. it divides the entire app into various bundles to manage its speed. So, all the components related to the active route will be loaded. Lazy Loading in Angular is used only at the start of the application. Once the application begins and the user starts navigating, it will load immediately.
Visit Angular documentation and explore more regarding its features.
Here is the Primary Implementation in Your Angular Modules Best Practices(1) In your app routing file, use loadchildren rather than a component. const routing: Routes = [ { path: 'items', loadChildren: () => import('./data/data.module'). then(d => d.DemoModule) } ];
Now, add the route of that particular component in the routing module for the Lazy Loaded module.
const routing: Routes = [ { path: '', component: DemoComponent } ];
4. Prevent Memory Leaks Observable Memory Leaks are commonly noticed in almost all frameworks and libraries. Angular also has the same issue. Angular Observables mainly streamlines whole data, but memory leaks can be caused if you are not attentive enough. Memory Leaks are one of the severe and harmful problems attacking the application’s security. Here are some suggestions to secure your application – – Use of async pipe You can use an async pipe and promise to prevent memory leaks. You should try your best to avoid subscribing to observables and then binding them with the components.
So, the conclusion is if the observable technique is not entirely done, the chances of memory leaks are likely to occur. â&#x20AC;&#x201C; Use of take(1) take(1) is an operator. It takes the value and allows for not subscribing whenever a new value is diagnosed. It takes care that you receive data only once. It prevents leaking of memory in an efficient way. info$.pipe(take(1)).subscribe((response)=>co nsole.log(response)) â&#x20AC;&#x201C; Use of takeUntil takeUntil is also an operator. It allows monitoring the Observables and get rid of the subscriptions once the value is emitted by Observables. We can conclude that it secures the Observables from getting leaked.
export class DemoApp implements OnInit, OnDestroy { constructor(private route: ActiveRoute, private http: Http) { } ngOnInit() { this.route.params .takeUntil(destroyedComp(this)) .subscribe(param => { // write code here... }); this.http.get("/loading") .takeUntil(destroyedComp(this)) .subscribe(res => { // write code here... }); } ngOnDestroy() { // empty } }
5. Declaring Variable Types Rather Than Using any At the time of Angular code review, I have observed many developers using ‘any’ as variable types, which is not one of the Angular best practices. The thing with ‘any’ is that Angular will assume the variable’s type based on that particular variable’s value. So, you have to be doubly sure when you use ‘any’ to declare a variable, or else it could cause some small bugs that can be hard to debug. Let’s take an example here – If you have this code.
let a = 10; let b = 'xyz'; let c = a + b; console.log(`Value of c: ${z}` // Output Value of c: 10xyz
In the above code, the output will be as expected. But, if you have code like this â&#x20AC;&#x201C; let p: number = 10; let q: number = 'xyz'; let r: number = a + b; // compile error: Type '"xyz"' is not assignable to type 'number'. let s: number
You might not get the expected value all the time. To avoid that, you can use number instead of any.
6. Angular Coding Practices and Folder Structure Most of the developers tend to overlook the importance of standard coding practices. But, very few realize that following the code styles can help their fellow developers for code review quickly and adequately. It is not just for Angular; you should try to follow the coding practices in any programming language you are using. It increases the understandability, readability, simplicity, and adaptability of your project.
Here are some coding standards you can keep in your mind â&#x20AC;&#x201C; Every single file should have code lines within 400. Every single function should have the code lines within 75. For different slider components, use a custom prefix. Utilize const if the values are constant throughout the file. Names of functions should be meaningful and in the lower camel case. Always have a habit of leaving an empty line between all the imports and modules; once you are done importing all the third-party applications, leave a blank line and then start with modules/custom modules.
Folder structure â&#x20AC;&#x201C; Creating a Folder structure is again a simple but important thing to follow. It helps to have a clear idea of the components in the application. If you have not correctly structured your folder, then you can be in trouble for managing the whole application. Irrespective of the size of projects, you should always try to have the habit of structuring your project.
7. Utilize Central State Management (Redux/Ngrx)
State management is manageable when you are dealing with small or medium-sized Angular applications, but as the size of the application grows, the process becomes quite tricky and hectic. There are so many components having their local states, and you need to have smooth communication between these components. It is advisable and considered one of the Angular best practices to use central state management. Now you might be wondering what central state management is? Here is the answer â&#x20AC;&#x201C; Central State Management means having all the states of the components in one place, no need of dividing it among various small components unless thereâ&#x20AC;&#x2122;s a requirement for it. As the state of the entire application is managed in one place, it makes the communication between components a lot easy.
Advantages of Central State Management â&#x20AC;&#x201C; No need to search the component tree, as the state is managed in one place It makes the transfer of data easy The main issue of communication between the component to component is solved if your application has a centralized state It makes debugging less time taking
You have two great options for your Angular application â&#x20AC;&#x201C; Redux and Ngrx.
The answer to which one you should prefer altogether depends on your projectâ&#x20AC;&#x2122;s requirement, size of the application, and technology stack. If you are dealing with large applications where you have hundreds of components to deal with, then redux is the best for you. But, if you are dealing with small or medium-sized applications, Redux should be prevented. Considering redux for such applications can indeed cause performance issues and further complicates the code.
Take away So, this was all about the Angular architecture, Angular code review checklist, and Angular best practices to improve your Angular code. I hope the purpose of landing on this blog has served as per your expectations. As I said before, you should try to develop coding practices in any technology or framework, which enhance the performance, readability, and understandability of the application. Best applications are developed when developers focus on how to code and what not to code.
If you are looking for a helping hand to improve your Angular application performance, hire angular developer from us today. Our Angular programmers are well-versed in fulfilling all your custom Angular code requirements. Get in touch with our dedicated Angular developers to make your existing Angular application clean and performant.
Thank You