All of the above answers explain OnPush and Default , here I am posting an example of how this works: https://plnkr.co/edit/hBYb5VOrZYEsnzJQF5Hk?p=preview
user-one.component.ts:
import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'user-one', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <div> <h4>{{ user.name }}</h4> <h5>{{ user.age }} years old</h5> {{ user.location }} <br /> {{ user.email }} <button (click)="update()">Internal update</button> <p>* should not update</p> </div> ` }) export class UserOneComponent { @Input() user; update() { this.user.name = 'Lebron James'; } }
user-two.component.ts:
import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'user-two', changeDetection: ChangeDetectionStrategy.Default, template: ` <div> <h4>{{ user.name }}</h4> <h5>{{ user.age }} years old</h5> {{ user.location }} <br /> {{ user.email }} <button (click)="update()">Internal update</button> <p>* should update</p> </div> ` }) export class UserTwoComponent { @Input() user; update() { this.user.name = 'Kevin Durant'; } }
Each time we change the properties of an object, such as "this.user.email" or "this.user.name", UserTwoComponent will always update the changes, but UserOneComponent only changes when we have a new user object.
If you change the properties inside each component, it inherits ChangeDectectionStrategy, for example, if we change this.user.name inside UserOneComponent, both names in UserOneComponent and UserTwoComponent would change, but if we change the name inside UserTwoComponent, then only the name inside UserTwoComponent would change
haifzhan Nov 07 '17 at 5:39 on 2017-11-07 05:39
source share