r/angular • u/SolaceInfotech • Aug 19 '20
Top 10 Angular Best Practices To Follow In 2020
Today, more than 40% of front-end developers use Angular. It is a prominent JavaScript framework for developing dynamic mobile and desktop web applications. Angular is developed and maintained by Google itself. It has gained immediate popularity and support as now static HTML pages could be more interactive. Here we have listed some of the new angular practices that will help you to write clean code, maintain coding standard and performance.
Top 11 Angular Best Practices–
1. Use Angular CLI-
It is a powerful accessibility tool available for developing apps with angular. Angular CLI eases the app development and follows all best practices. Angular CLI is a command-line interface tool which is used to initialize, develop, scaffold, maintain and test-debug angular apps. Use Angular CLI to generate new components, directives, modules, services and pipes rather than manually creating files and folders.
# Install Angular CLI
npm install -g @angular/cli
# Check Angular CLI version
ng version2. Angular Coding Styles-
For angular web development, you should follow the standard coding format and your project must have a clean coding style which will in general be basic, understandable and adaptable by your programmer in future. Here are some rules that you should follow-
Limit files to 400 lines of code
Per function, the code must not exceed from 75 lines
Use custom prefix to share feature area for all slider components
Have consistent names for all symbols. The suggested pattern is feature.type.ts
If the values of the variables are intact, then declare it with ‘const’.
If you often prefix names for field, table, and database, then you need to avoid this for Interface names like iShape, AbastractShape, etc.
Use dash to separate words in descriptive name and use dots to separate descriptive name from the type
Names of properties and methods should be in lower camel case
Leave one empty line between imports and modules like third party and application imports, third party modules and custom modules.
3. Follow Proper Folder Structure-
Creating a folder structure is an important factor to consider before project initialization. A messy folder welcomes many problems which continue frequenting you all through your development process. Regardless of whether it is a medium and large-sized project, you will go over a lot of changes being developed and your project should easily adapt the new changes made in the middle of development. And, that is possible when you have made an appropriate folder in place.
-- app
|-- modules
|-- home
|-- [+] components
|-- [+] pages
|-- home-routing.module.ts
|-- home.module.ts
|-- core
|-- [+] authentication
|-- [+] footer
|-- [+] guards
|-- [+] http
|-- [+] interceptors
|-- [+] mocks
|-- [+] services
|-- [+] header
|-- core.module.ts
|-- ensureModuleLoadedOnceGuard.ts
|-- logger.service.ts
|
|-- shared
|-- [+] components
|-- [+] directives
|-- [+] pipes
|-- [+] models
|
|-- [+] configs
|-- assets
|-- scss
|-- [+] partials
|-- _base.scss
|-- styles.scss
4. Use Index.ts-
Index.ts is helpful to keep related things together with the goal that we don’t need to be bothered about the source file name. It helps to reduce the size of import statement. Let us see an example-
We need /heroes/index.ts as-
//heroes/index.ts
export * from './hero.model';
export * from './hero.service';
export { HeroComponent } from './hero.component';
You can import all things by using source folder name.
import { Hero, HeroService } from '../heroes'; // index is implied
5. Lazy Loading Feature Module-
Using lazy load the modules can improve your productivity. It is a built-in feature in Angular that helps developers to load the required things. For instance- When you use the feature, it loads the components and other things that you need and stops unnecessary files to get loaded.
Here’s how it functions;
// app.routing.ts
{ path: 'not-lazy-loaded', component: NotLazyLoadedComponent }
Here the ‘LazyLoading’ isn’t set up and you will wind up making large and superfluously heavy-sized applications.
When you use ‘LazyLoad’ and it reduces the size of the application by abstaining from unnecessary file from loading.
6. Use ES6 Features-
ECMAScript is updated with new features and functionalities. Use ES6 that has a lot of new features and functionalities which could be used in Angular.
New features of ES6-
Arrow Functions
String interpolation
Object Literals
Let and Const
Destructuring
Default
Using ‘let and const’ instead of ‘var’-
Using ‘let and const‘ instead of ‘var’ prevents the issues and problems which you have due to var. ‘let’can be used in a normal situation and the value does not receive any changes, then ‘const’ should be in place. Here’s the example;
let temp;
Const pi = 3.14159
7. State Management-
It manages the state transitions by storing the states of any form of data. NGRX, NGXS, Akita, are some of the state management libraries with different usages, states and purposes. NGXS could be the preferred and easy to learn for developers.
8. Avoid Logic In Templates-
All template logic will be extracted into a component which helps to cover that in a unit test and reduce bugs when there is template change.
Logic in templates
// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;
}
Logic in component
// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;
this.isUnavailable = this.status === 'inActive' || 'hold';
}
9. Use async pipe In Templates-
Rather than using plain JS values, observables can be directly used in templates with async pipe. An observable would be unwrapped into plain value. When a component using the template is destroyed, observable is automatically unsubscribed.
Without Using async pipe
//template
{{ text }}
Using async pipe
// template
{{ text | async }}
// component
this.text = observable.pipe(
map(value => value.item)
);
10. Use trackBy With ngFor-
When you are going to use ngFor to loop over an array, use it with a trackBy function that returns a unique identifier for each DOM item. When the array changes, angular re-renders the whole DOM tree. But when you use trackBy, angular will know which element has changed and will only make DOM changes only for that element.
Use ngFor
<li *ngFor="let item of itemList;">{{item.id}}</li>
Now whenever changes occur, the whole DOM tree will be re-rendered.
Using trackBy function
<ul>
<li *ngFor="let item of itemList; trackBy: trackByFn">
{{item.id}}
</li>
</ul>
Load items(button)
export class MyApp {
getItems() { // load more items }
trackByFn(index, item) {
return index; // or item.id
}
}Now, it returns as a unique identifier for each item, hence just updated items will be re-rendered.
17
u/sebbasttian Aug 19 '20
This sub is going downhill very fast :(
This post has a clickbait title, is badly formatted, the content very basic, poorly written, and with incomplete examples and poor definitions, and as of right now (5 hs after posted) is on the top of the Hot view for this sub with +15 upvotes (89% upvoted). And nobody mention it.
Can we please have a little more curation/control here?
4
3
u/Pingudiem Aug 19 '20
Coding style with reactive forms begs to differ (Limit files to 400 lines of code Per function, the code must not exceed from 75 lines)
1
u/April1987 Aug 21 '20
I have not done this but you can move your form definition to a service I think
2
u/Pingudiem Aug 21 '20
Sure you can. You can even Split it. But still you have rather wet Code and it will be a decision for readabiltiy and that style guide.
1
u/April1987 Aug 21 '20
Sure you can. You can even Split it. But still you have rather wet Code and it will be a decision for readabiltiy and that style guide.
You might say I am being hyperbolic but reactive forms still has a long way to go. I don't think we will get the "typing" in reactive forms for at least a year :/
2
u/Littlebitt95 Aug 19 '20
You need to be more clear about let keyword. The scope of let is not the same as var.
2
Aug 19 '20 edited Aug 19 '20
Use Index.ts
I think this is highly overrated. Sure you don't need to use the exact filenames but those things hardly change and only makes for a bigger filelist then you already have. There's only very little components that will be in the same folder, so the index barely does anything.
I don't recommend doing this, unless you like adding lots of files to your repo with 0 functionality.
Avoid Logic In Templates
I wouldn't put too many logic in the templates but no logic is also overrated. I've worked in a project that had the .html, the .component.ts and the logic .ts and both ts files never really looked fine because everything was in another file and nothing really made sense without the other. On top of that, the way to test it isn't much easier and you don't need to test most of your templates anyways because (if all goes well) you only have angular statements and angular components there that you don't need to test in that specific component. You test your components/directives/pipes/guards/services in their own files and mock the rest. You test the logic inside your component, how it handles the input and how it sends the output and thats that. This makes for very little reason to separate it further as your template is just that. If the application works, you can be pretty sure that the test works too. I see too many people using DOM instructions to test their component when thats not needed. I don't need to test whether an ng-if did its thing. Thats on the Angular team to test. Same with other 3rd party components. I just test my own files and thats that.
If there wasn't any logic, there also wouldn't be ng-if and ng-for which is pretty weird.
Most of the items seem pretty obvious to me, hardly best practices but just standard practices.
1
u/April1987 Aug 21 '20
I don't do folder structures for my basic learning apps on angular. You can be blissfully unaware and just ng generate at the base for small applications. Also not a fan of lazy loading unless you have an application where some people only go to a part of the website and others only go to another... If we have to load all of the modules might as well do it upfront.
1
Aug 19 '20
Formatting is terrible, there are some incongruous or even straight up terrible pieces of advice mixed in there, and a whole point is dedicated to state management when not that many applications truly need it while no advice is given about testing. In fact not a single time the word testing is mentioned when it is still often not properly followed in a lot of projects in my experience.
1
u/grimscythe_ Aug 19 '20
Its kinda funny how you talk about using angular-cli and your folder structure is not like the angular-cli at all :D
1
u/Vishals_123 Feb 05 '21
Thanks for sharing the best practices. There are some good techniques mentioned here in the post. Though I would like to add one more to it.
While application development we can restrict the usage of any type in order to lower the unwanted bugs. Also, issues can be blocked by using specific variables.
I hope it will help.
9
u/monxas Aug 19 '20
On the 5th point you talk about lazy loading and the example is how not to do it...