17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 19: Optimizing rendering using<br />

ChangeDetectionStrategy<br />

Section 19.1: Default vs OnPush<br />

Consider the following component with one input myInput and an internal value called someInternalValue. Both of<br />

them are used in a component's template.<br />

import {Component, Input} from '@angular/core';<br />

@Component({<br />

template:`<br />

<br />

{{myInput}}<br />

{{someInternalValue}}<br />

<br />

`<br />

})<br />

class MyComponent {<br />

@Input() myInput: any;<br />

someInternalValue: any;<br />

}<br />

// ...<br />

By default, the changeDetection: property in the component decorator will be set to<br />

ChangeDetectionStrategy.Default; implicit in the example. In this situation, any changes to any of the values in<br />

the template will trigger a re-render of MyComponent. In other words, if I change myInput or someInternalValue<br />

angular 2 will exert energy and re-render the component.<br />

Suppose, however, that we only want to re-render when the inputs change. Consider the following component with<br />

changeDetection: set to ChangeDetectionStrategy.OnPush<br />

import {Component, ChangeDetectionStrategy, Input} from '@angular/core';<br />

@Component({<br />

changeDetection: ChangeDetectionStrategy.OnPush<br />

template:`<br />

<br />

{{myInput}}<br />

{{someInternalValue}}<br />

<br />

`<br />

})<br />

class MyComponent {<br />

@Input() myInput: any;<br />

someInternalValue: any;<br />

}<br />

// ...<br />

By setting changeDetection: to ChangeDetectionStrategy.OnPush, MyComponent will only re-render when its inputs<br />

change. In this case, myInput will need to receive a new value from its parent to trigger a re-render.<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 90

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!