angular2 changedetection - Angular change detection process repaint the dom -


i'm learning angular change detection process , checking dev tools in chrome, see strange behavior.

my plnkr demonstrate behavior: http://plnkr.co/edit/ctlf00nqdhvmkhyc8iou

i have simple component view:

<li *ngfor="let item of list">{{item.name}}</li> 

and constructor:

constructor() {     this.list = [{name: 'gustavo'}, {name: 'costa'}] 

to simulate simple request added:

// simulating request repaint dom setinterval( () => {   this.list = [{name: 'gustavo'}, {name: 'costa'}]; }, 2000); 

if noticed, array list receives list equal initial value. let's imagine when angular checks values in view in change detection process have code this:

if( oldname !== name )  { // ( 'gustavo' !== 'gustavo')  // update view } 

but values same, why angular repaint dom every 2 seconds.?

but if i mutate object, repaint not occurs

// simulating request there not repaint setinterval( () => {   this.list[0].name = "gustavo"; // no repaint because it's same value   this.list[1].name = "costa 2"; // repaint }, 2000); 

you can test plnkr link above.

this because angular uses default trackbyfunction defaultiterablediffer tracks items identity.

const trackbyidentity = (index: number, item: any) => item; 

so when create new array creates new object references , angular detects changes. if didn't change array reference, angular still think items changed because object references change:

setinterval( () => {   this.list.length = 0;   this.list.push({name: 'gustavo'});   this.list.push({name: 'costa'}); }, 2000); 

you can provide custom trackbyfunction track object name:

@component({   selector: 'my-app',   template: `    <li *ngfor="let item of list; trackby:identify">{{item.name}}</li>   ` }) export class app {   list:[];    identify(index, item){      return item.name;    } 

in way dom not updated. see this plunker.

since curios ngfor can read this answer explain how ngfor works under hood.


Comments

Popular posts from this blog

Ansible warning on jinja2 braces on when -

Parsing a protocol message from Go by Java -

html - How to custom Bootstrap grid height? -