Use the trackBy
function when using ngFor
Angular will keep track of changes and only re-render changed elements
// in the template
<li *ngFor="let item of items; trackBy: trackByFn">{{ item }}</li>
// in the component
trackByFn(index, item) => return item.id; // unique id corresponding to the item
When declaring variables, use const
when the value is not going to be reassigned.
DON'T observable.map()
DO observable.pipe(map())
Use the async
pipe in templates to subscribe to Observables instead of in the component.
Lazy load where possible for performance
Business logic should be contained in services (or utils, not preferable), we want to keep these separate.
Avoid using &&
clauses and other similar logic:
DON'T: <p *ngIf="role==='developer'"> Status: Developer </p>
DO: <p *ngIf="showDeveloperStatus"> Status: Developer </p>
DO declare and export components
, pipes
, directives
.
DO import and export other shareable modules like FormsModule
or CommonModule
DON'T declare services or singletons here. These should be imported in the CoreModule
.
DO import modules that should be instantiated once in your app. DO place services in the module, but do not provide them.
Create an index.ts
for simplifying imports/exports of components.
Example
Add aliases for commonly used paths
{
...
"compilerOptions": {
...
"baseUrl": "src",
"paths": {
"@env": ["environments/environment"],
"@shared/*": ["app/shared/*"],
"@core/*": ["app/core/*"]
}
}
}
We don't like to repeat ourselves, so any color or other variables should be defined in /styles/utilities/variables.scss
When subscribing to observables, always make sure you unsubscribe from them appropriately by using operators like take
, takeUntil
, etc. Failing to unsubscribe may cause unwanted memory leaks.
private _destroyed$ = new Subject();
public ngOnInit (): void {
iAmAnObservable
.pipe(
map(value => value.item)
// We want to listen to iAmAnObservable until the component is destroyed,
takeUntil(this._destroyed$)
)
.subscribe(item => this.textToDisplay = item);
}
public ngOnDestroy (): void {
this._destroyed$.next();
this._destroyed$.complete();
}