Skip to content

Best Practices

Angular

Avoid myfunc.bind(this) in HTML-Template.
Why? It creates a new function for every rendering.

Do minimize the use of functions in HTML-Template.
Why? They get executed for every rendering.

Do replace functions in template with (pure) pipes.
Why? Function calls made from a template are invoked every time a change occures (no caching) => getting called very often.
Why? Pipes are only called when inputs (to pipe function) are changed.
Consider Using Memo Decorator (npm package) to cache pipe outputs.

Do use trackBy along with ngFor.
Why? When an 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.

Do use aliases for importing modules or libraries.

Do use async-pipe in view and pass value to action instead of directly working on the stream within the action.

Typescript

Avoid using any.
Why? It creates enormous bug opportunity.

Do define DTOs as interfaces instead of classes.
Why? A class generates code since it is primarily syntactical sugar over JavaScript’s existing prototype-based inheritance.
Why? An interface does not generate code since it is a virtual structures that only exist within the context of TypeScript.

rxjs

Do use Marble Diagrams to understand rxjs (e.g. https://rxmarbles.com/, https://rxjs-dev.firebaseapp.com/api).

Do unsubscribe from observables (e.g. by calling unsubscribe(), using an operator that completes the stream, using the async pipe).
Why? It prevents memory leak.

Do use async pipe.
Why? It simplifies code by automatically un-/subscribing from the observable.
Why? It allows OnPush change detection strategy.
Consider *ngIf “as” or hot observables to prevent multiple execution of observables.

Avoid nested subscriptions.
Why? It makes the code unreadable, complex, and introduces side effects.

Avoid logic inside the subscribe function.
Why? The reactive workflow and its benefits ends by subscribing to an Observable.

Do pass values to components and services instead of observables.
Why? It reduces coupling.
Why? It prevents unwanted side-effects.