This summer me and Roman started a series of tweets with helpful tips and tricks about Angular. It was met well by the community so I decided to write an article follow-up. Here are 5 generalized advises I want to give to Angular developers across the globe. These advises are backed by some concrete examples pulled from our Twitter activity. They can help you improve your developer skills or give you some practical tricks at the very least.

1. Know how change detection works in Angular

There are many great articles going deep into change detection mechanism. Like this one. So let’s just recap the basics quickly and get to the tips.

Recap

Angular has two change detection modes: Default and OnPush. First one triggers change detection for every tick happened anywhere in the app. Former only marks view for checking if an event has happened in this view or if input data has changed.

Default vs OnPush

There’s really no reason for you to use Default. All you need to do is write your code the way framework expects it to and you won’t get into trouble with OnPush. This means, you should never mutate your data. If your input arrays or objects change immutably, OnPush would pick this up and refresh the view.

When you subscribe to events with @HostListener Angular has got you covered as well. But what if you are working with RxJS streams? You can always inject ChangeDetectorRef and do markForCheck() when you need it. But a declarative option would be to end up with async pipe in your template. It would trigger change detection on each emit.

You might have seen this pattern:

<div *ngIf="stream$ | async as result">
    ...
</div>
<>

But what do you do when you need falsy results too? You can strip condition logic from ngIf and create a simple structural directive. It would be used only to add context to the view:

NgZone#

If you cannot fully switch to OnPush there are still things you could optimize. You can inject NgZone and do performance sensitive actions in .runOutsideAngular(). This way there will be no extra ticks in the change detection mechanism. Even components with Default strategy will not perform change detection cycle. You should do this for events that trigger rapidly like mousemovescroll. To do it declaratively with RxJS streams you can create two operators. One for leaving the zone and another to return to it if you need to trigger change detection:

#angular #typescript #dependency-injection #rxjs

5 tips to boost your Angular skills
1.35 GEEK