Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: What does binding event to 0 mean?

I am learning Angular 2 from the official guide. I came across the following piece of code.

    @Component({
  selector: 'loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent { }

As you see in the template keyup event is bound to 0, (keyup)="0". I don't understand what it means when an event is bound to a number. In doc it says that

code binds the keyup event to the number 0, the shortest template statement possible. While the statement does nothing useful, it satisfies Angular's requirement so that Angular will update the screen.

I delved over internet also but could not find any explanation regarding to binding events to number. Can anyone please help me on this? Thanks.

like image 917
Hitesh Kumar Avatar asked Oct 29 '25 06:10

Hitesh Kumar


2 Answers

(keyup)="0"

means, when that event happens, then return 0, which is quite equivalent to "do nothing". There is no shorter way of expressing that, except not adding any event binding at all.

The event binding is used in that example to cause change detection to run, which is by default run every time an event handler was called.

Without the event binding, there is no event handler and Angular won't run change detection, which will cause {{box.value}} to not update the value.

like image 101
Günter Zöchbauer Avatar answered Oct 31 '25 18:10

Günter Zöchbauer


It was not clear for me as well, because I thought that Angular triggers the change detection on any asynchronous event. For example Angular University states that:

The following frequently used browser mechanisms are patched to support change detection:

  • all browser events (click, mouseover, keyup, etc.)
  • setTimeout() and setInterval()
  • Ajax requests

But it's not a whole truth, because official documentation says that:

Angular updates the bindings (and therefore the screen) only if the app does something in response to asynchronous events, such as keystrokes. This example code binds the keyup event to the number 0, the shortest template statement possible. While the statement does nothing useful, it satisfies Angular's requirement so that Angular will update the screen.

So apparently an asynchronous event must be handled in the application in order to trigger the change detection, hence (keyup)="0"

like image 33
anth Avatar answered Oct 31 '25 20:10

anth