Angular Best Practices Guide
Angular Best Practices Guide
following in
Angular
Development
www.ideas2it.com
Angular is an open-source front-end framework developed
by Google for creating dynamic, modern web applications.
Introduced in 2009, Angular’s popularity is based on its
eliminating unnecessary code and ensuring lighter and
faster apps. Having rapidly evolved from AngularJS in 2010,
the front-end framework is today used by more than 40%
of software engineers for creating user interfaces.
2
1. Use Angular CLI
ng version
3
2. Maintain proper folder structure
-- 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
|
4
|-- shared
|-- [+] components
|-- [+] directives
|-- [+] pipes
|-- [+] models
|
|-- [+] configs
|-- assets
|-- scss
|-- [+] partials
|-- _base.scss
|-- styles.scss
5
3. Follow consistent Angular
coding styles
6
4. Typescript
Type-checking
7
5. Use ES6 Features
Arrow Functions
String interpolation
Object Literals
Destructuring
Default
8
6. Use trackBy along with ngFor
Use ngFor
<ul>
<li *ngFor="let item of itemList;">{{item.id}}</li>
</ul>
<ul>
<li *ngFor="let item of itemList;">{{item.id}}</li>
</ul>
Now, each time the changes occur, the whole DOM tree will be
re-rendered.
9
Using trackBy function
<ul>
<li *ngFor="let item of itemList; trackBy: trackByFn">
{{item.id}}
</li>
</ul>
<button (click)="getItems()">Load items</button>
trackByFn(index, item) {
return index; // or item.id
}
}
10
7. Break down into small reusable
components
Parent Component
Title Component
Body Component
List Component
List Component
List Component
Footer Component
11
8. Use Lazy Loading
// app.routing.ts
{
path: 'without-lazy-loaded',
component: WithoutLazyLoadedComponent
}
// app.routing.ts
{
path: 'lazy-load',
loadChildren: 'lazy-load.module#LazyLoadModule'
}
12
// lazy-load.module.ts
@NgModule({
imports: [
RouterModule.forChild([
{
path: '',
component: LazyLoadComponent
}
])
],
declarations: [
LazyLoadComponent
]
})
export class LazyModule { }
13
9. Use Index.ts
//heroes/index.ts
14
10. Avoid logic in templates
// template
<span *ngIf="status === 'inActive' || 'hold'"> Status:
Unavailable </span>
// component
ngOnInit (): void {
this.status = apiRes.status;
}
Logic in component
// template
<span *ngIf="isUnavailable"> Status: Unavailable </span>
// component
ngOnInit (): void {
this.status = apiRes.status;
this.isUnavailable = this.status === 'inActive' ||
'hold';
}
15
11. Cache API calls
We can introduce a cache time for some API calls the value
change, but not frequently. Caching API calls and avoiding
unwanted duplicate API calls improves speed of the
application and also ensures we do not download the
same information repeatedly.
16
12. Use async pipe in templates
//template
<p>{{ text }}</p>
// template
<p>{{ text | async }}</p>
// component
this.text = observable.pipe(
map(value => value.item)
);
17
13. Declare safe strings
The variable of type string has only some set of values and
we can declare the list of possible values as the type. So the
variable will accept only the possible values. We can avoid
bugs while writing the code during compile time itself.
18
14. Avoid any type
interface IProfile {
id: number;
name: string;
age: number;
}
constructor() { }
ngOnInit() {
this.userInfo = {
id: 12345,
name: 'test name',
mobile: 121212
19
}
}
}
// Error
20
15. State Management
21
16. Use CDK Virtual Scroll
//Template
<ul>
<cdk-virtual-scroll-viewport itemSize="100">
<ng-container *cdkVirtualFor="let item of items">
<li> {{item}} </li>
</ng-container>
</cdk-virtual-scroll-viewport>
</ul>
// Component
export class CdkVirtualScroll {
items = [];
constructor() {
this.items = Array.from({length: 100000}).map((_, i)
=> `scroll list ${i}`);
}
22
17. Use environment variables
Dev environment
Dev environment
24
19. Always Document
/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
return bar.toString()
}
25
contact@ideas2it.com