Reputation: 784
My questions relates to Angular(2) using a RC1 fork from angular.io sample plunkr. The data binding function within the ngFor template runs as if change detection is found to be true on any event outside of the ngFor. In my example, a click of a button outside of the ngFor.
I have tried with and without the trackBy function (though its poor documentation currently so not sure if I'm using it right); I cannot figure out how to make sure every action doesn't cause a redraw of the ngFor since this could be very costly.
Result of log when clicked:
You can see the problem live on this plunkr by watching the console log:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<button (click)="clickOustideFunction()" >hi</button>
<h1 *ngFor="let d of data;trackBy:a">
My First Angular 2 App{{drawingForFunction()}}
</h1>`
})
export class AppComponent {
data= [{"a":1}, {"a":2}];
clickOustideFunction(): void {
console.log("button");
}
drawingForFunction(): void {
console.log("drawing");
}
}
Upvotes: 1
Views: 905
Reputation: 364677
By default, all template bindings are checked for change after each event. Normally an NgFor loop will have bindings like {{data.a}}
, and those bindings are all dirty checked each time change detection runs. If you have a function instead, like {{drawingForFunction()}}
, those functions will also be evaluated each time change detection runs.
Angular will only modify the DOM if it sees/detects a change, hence nothing will re-render unless there is a change. And only the items that changed are re-rendered (not the entire view).
You might be able to use the OnPush
change detection strategy to reduce how often your component is checked for changes.
Upvotes: 2