Search code examples
angulardata-binding

Angular one way binding updates the view only once


I'm trying to understand how Angulars one way binding works. In the following code the button only updates the view once and in subsequent clicks has no effect of the view. Can someone please explain why it works like this? It looks to me as the databound obj is set to a new reference object each time the button is clicked. Shouldn't then the view be updated each time the button is clicked?

Template:

<div *ngIf="obj;">
   <input #testInput [value]="obj.testValue">
   <button (click)="onClick(5)"></button>
</div>

Typescript:

export class TempComponent {
   constructor() {}

   obj = { testValue: 1 };

   onClick(value: number): void {
       this.obj = { testValue: value };
   }
}

Solution

  • This works only once because you are not updating the value when the user changes the value in the input (2-way-binding). Angular compares the value it knows (which is 5 after the first click) with the new value (which is also 5) and determines it does not need to reflect the change in the view because the values are the same. Try it with a different value each time and you will see the difference.

    Working Stackblitz with randomized numbers.