5

In my app, conditionally i am adding a class. and when the user enter something i am checking the value and accordingly i am adding the class name. it works fine.

but it only updates on set of (keyup)='0' - setting some value on keyup. this is not like angular 1 here.

so any one explain me why do we set the (keyup)=0 here? and what it do for us?

here is my code :

import {Component} from "angular2/core"

@Component({

    selector : 'my-component',

    template : `
                <h2>My Name is: {{name}} 
                    <span [class.is-awesome]="formReplay.value === 'yes' ">So good</span>
                </h2>
                <input type="text" #formReplay (keyup)="0" />
                `,

    styles  : [`

        .is-awesome{
            color:green;
        }

    `]

})

export class MyComponent { 
    name = "My Name";   
}
user2024080
  • 1
  • 14
  • 56
  • 96
  • 1
    Nothing, that keyup is doing nothing but triggering change detection. The `0` means nothing since having an empty event [produces an error](https://github.com/angular/angular/issues/3754). – Eric Martinez Mar 15 '16 at 02:54

1 Answers1

9

Offical docs

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

look for this in offical docs.

This won't work at all unless we bind to an event.

Angular only updates the bindings (and therefore the screen) if we do something in response to asynchronous events such as keystrokes.

That's why we bind the keyup event to a statement that does ... well, nothing. We're binding to the number 0, the shortest statement we can think of. That is all it takes to keep Angular happy. We said it would be clever!

micronyks
  • 54,797
  • 15
  • 112
  • 146
  • Yes it is there Eric ! :-) – micronyks Mar 15 '16 at 03:47
  • A better solution is here - http://stackoverflow.com/a/35368127/968003. ` {{mymodel}}` The current one doesn't work for `input[type="number"]` when instead of entering a value, the user clicks on the up/down arrow. Then the value in the input is changing, but the `keyup` event isn't firing up. – Alex Klaus Dec 31 '16 at 02:20
  • Why are we binding to a statement? In the docs it says we have to bind to an event. Why do we even have to bind keyup to anything if we have a template reference variable? – Patrick Jul 11 '18 at 05:49