Angular: Change Detection during OnPush

Consider a parent & child component. Child receives “data” Object as Input from parent.

Parent

Child

<div>

<child [data]=”name”></child>

</div>

 

name = { someKey: “someVal” }

 

<h1> {{ data.someKey }} </h1>

 

@Input data = {someKey: null}

 

Now if a button is introduced in Parent element to change the data of the @Input object present in child,

Parent:

 

Parent

 

<div>

  <child [data]=”name”></child>

  <button (click)=”editData()”> edit </button>

</div>

 

editData() { this.name.someKey = “new Value!” }

Output:

 

New Value!

  Edit     .   

 

Using OnPush in child

selector: ‘child’,

template: `{{ data.someKey }}`

changeDetection: changeDetectionStrategy.OnPush

 

Now, the edit button will not update to “new Value” in child. Because the reference to @Input() has not changed. Only the object inside it has changed. In order to change the “reference”, create a copy of this old object (using spread operator) and update the required value. Now assign this new object to @Input data.

let newObj = {…this.name}

newObj.someKey = “new Value!”

this.name = newObj;

 

Now it works!


Comments

Popular posts from this blog

Inside the JavaScript Memory Box: Visualizing Variables, References, and Copies

React & State Management: All Concepts

React: Communication between components