2

We're supposedly not allowed to increment or set values in the property binding. In the official Angular2 docs, they claim that:

The expression could call something like getFoo(). Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more.

However, I did an example where I actually override the value and increase it, then set it to the DOM property and it all works well. Here's my code:

export class AppComponent {
  myIndex: number = 0;

  overrideMe(newValue:string) {
    this.myIndex = parseInt(newValue);
    this.myIndex++;
    return this.myIndex;
  }
}

and HTML:

{{myIndex}}

<input type="text" [value]="overrideMe(10)" />

In theory, this should be a bad practice and avoided, but in real life this works just as good. So my question is, what IS the correct case to represent that these things shouldn't be done?

uglycode
  • 3,022
  • 6
  • 29
  • 55

0 Answers0