Control bound to a model shows old value on certain keys despite get property() working in Angular

微笑、不失礼 提交于 2019-12-11 23:27:04

问题


First of all, sorry for the cryptic question. I'll update gladly if someone suggests something better. Perhaps it's my diagnostics that aren't well directed.

I have a config class that has a field. There's a input box bound to that field and, since the requirment is a bit complex, I implemented get and set methods for it. The design looks like this.

export class RowConfig {
  constructor(public amount = 0, ...) { }

  get rendition() {
    let output = "";
    if (this.amount !== null && this.amount !== undefined)
      output = ("" + this.amount)
        .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");

    console.log("rendition GET: " + this.amount + " -> " + output);
    return output;
  }
  set rendition(input: string) {
    console.log("rendition SET: " + input);
    const negative = input.match(/^[-]/);
    const digits = input.replace(/\D/g, "");
    let output = null;
    if (digits)
      output = +digits * (negative ? -1 : 1);
    this.amount = output;

    console.log("rendition ACT: " + output);
  }
}

At first, I assumed it was something with the regex (which it isn't). Then I though my model is bound in a way that get rendition() serves wrong value (which is doesn't). Clearly, the logic in the class performs as supposed to. However, when I enter 12345W, the non-digit character stays in the input box! I can see in the console that the received string 12345W is converted to and stored as the number 12345. I can also see in the console that the rendered value returned is 12 345, including the space, as supposed to.

Still, the value in the box shows W and I can't see why. When I eventually press a digit key, the control updates as expected and the non-digit is removed. So confused here...

<input #amount 
       type="text" 
       (keyup)="onKeyUp($event)"
       placeholder="xxx" [(ngModel)]="config.rendition">

I've tried acting on keyup, preventing defaults and stopping propagation. I've tried simplyfying the logic for when to alter the values. I can't see where I go wrong. The only suspicious thing I noticed is that get rendition() is called twice before and twice after the set rendition() is invoked (no that it tells me much and I can imagine it has to do with the Angular bubbling of events, somehow).

So at this point, I claim it's magic, the black kind. And I'll be greatly satisified if someone proves me wrong in this nice Blitzy.

来源:https://stackoverflow.com/questions/55994358/control-bound-to-a-model-shows-old-value-on-certain-keys-despite-get-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!