Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 Do we need avoid two way databind when not necessary?

I search a lot to understand if there is some bad performance if I use two way databind (ng-model) all times at my forms instead of one way databind. I know that with angular 1 for each two way databind a new watch is created and with huge applications with angular 1 we can have performance issues because this. Now I need to know if with angular 2 this does make some difference if I only use one way databind or not? Two way databind need to be avoid when not necessary?

like image 484
Gustavo Lira Avatar asked Sep 13 '16 01:09

Gustavo Lira


2 Answers

Angular2 doesn't really have two-way data binding.

Angular2 has

data-binding from parent to child

[childProp]="parentProp"

When change detection detects a change in parentProp it updates childProp and calls ngOnChanges() in the child component (when implemented).

and event binding from child to parent

The way from child to parent is event binding.

(childPropChange)="parentProp = $event"

calls "someActionOnParent()" when eventFromChild.emit(someValue) is called in the child component.

the combination of these two is just syntactic sugar for the data and event bindings shown above

[(childProp)]="parentProp"

This means change detection only has to check for parentProp to change and doesn't care about the other direction. The update from child to parent has to be invoked actively by the child component and doesn't involve change detection.

This unidirectional data flow allows Angular2's change detection to be extremely efficient. To further optimize change detection use ChangeDetectionStrategy.OnPush in your components. This allows to prune the tree where Angular2 has to actually do change detection.

like image 112
Günter Zöchbauer Avatar answered Sep 30 '22 14:09

Günter Zöchbauer


https://yakovfain.com/2015/12/29/two-way-data-binding-in-angular-2/

There are instances where 2-way data binding is best practice but specifically when you need real-time 2 way UI updates and other uncommon occurrences. The problem besides the extra work at digest is that you will be triggering tree traversals when unnecessary and it will ultimately slow down your app marginally but add enough of them and you will see the performance impact. Don't be scared to use them. Their impact is small on runtime but for best practice sake, use a one way data binding, set the changedetectionstrategy to on push and manually handle the observables yourself. Its easier said than done but if you can accomplish this you'll find you reduce unnecessary traversals drastically. Albeit the traversals are super lightweight but too much of anything is a bad thing and I don't like giving my application any autonomy.

like image 37
Mark Acosta Avatar answered Sep 30 '22 14:09

Mark Acosta