4 mistakes I have made while learning Angular and RXJS
Let me share a few mistakes I have made while learning Angular and RXJS.
I. π Using async
pipe for the same async source several times within one component template
<div>
<img [src]="asyncImgSrc | async" />
</div>
...
<div>
<img [src]="asyncImgSrc | async" />
</div>
In this case template will subscribe twice on asyncImgSrc
, so if we have http call there it will provoke two http requests β thas is not good, I guess.
π How to solve: use ng-template
, ng-container
with context definition and ngTemplateOutlet
:
<ng-template #layout let-src="src">
<div>
<img [src]="src" />
</div>
...
<div>
<img [src]="src" />
</div>
</ng-template><ng-container
*ngTemplateOutlet="layout; context: {src: asyncImgSrc | async}">
<ng-container>
II. π Forgotten unsubscribe from observables
π How to solve: RXJS takeUntil
operator placed last in every pipe with some subject as a parameter that gets next value when component has been destroyed is a very nice solution. Good links about this topic are: Stackoverflow answer and Angular In Depth blog.
III. π Using getters for in-template binding
There is an interesting conversation about such approach at Angular GitHub. I tried the example: adding simple loop in the getter froze Chrome forever π. Even OnPush
Change Detection Strategy does not solve a problem. But the recommendation that is given by above link π does:
never bind to functions if it can be avoided.
I learned it from my team lead: we canβt know how our code will grow, so letting things simple can save us from problems.
IV. π Direct DOM changes
this.element.nativeElement.innerHtml = ...
Stop. I heard: βstop!β. What is temptation to do this way after Angular.js!
Team lead just used createEmbeddedView
instead π and avoided uncotrolled behaviour of new markup. No words.
This short note frees my head from excess information and prevent me from repeating mistakes in future. Will think more π. Thank you for reading.