Angular Best Practices
Getting Setup
Naming
Keep with the style guide. E.g. catalog.component.ts which has CatalogComponent inside.
File Structures
LIFT,
- Locate Code Quickly
- Identify code at a glance
- Flattest structure possible
- Try to be DRY
General Coding
Single Responsibility
The single-responsibility principle (SRP) is a computer-programming principle that states that every module, class or function in a computer program should have responsibility over a single part of that program's functionality, which it should encapsulate. All of that module, class or function's services should be narrowly aligned with that responsibility.[1]
Symbol Naming
Stick with the naming conventions in the style guide. Generally for angular we use camel case.
Immutability
You should try and use this all the time in javaScript and typeScript. E.g.
Example 1
this.currentUser.classes.push(classId)
Best Practice would be
this.currentUser = Object.assign(
{},
this.currentUsers,
{
classes: this.currentUser.classes.concat([classId]}
})
Example 2
This is another example. Although the this.currentUser is assigned it is assign with an existing value user
saveUser(user): Observable<any> {
user.classes = user.classes || []
this.currentUser = user
return Observable.empty().delay(1000)
}
Best Practice
saveUser(user): Observable<any> {
user.classes = user.classes || []
this.currentUser = Object.assign(
{},
user,
{classes: user.classes || []}
)
return Observable.empty().delay(1000)
}
Why Immutability
The reason immutability is deemed to be good is because assignments of existing values are by reference which means in the example 2, if user which is passed in to saveUser changes outside of saveUser, the currentUser will change too.
Small Functions
Do not create large functions. In my view make minimum functions and separate flow code from calculation code.
Modules In Angular
Modules help
- single responsibility principle
- lazy loading
- managing resources, requirements
Standard approach is
- app module
- routing module
- core module (Services)
- shared module (Components, Directives and Pipes)
- n Feature modules