Angular2中ngModel比输入框晚一个字符。

3
我有一个输入框,我想在每次按键后验证输入。最终,当他们点击输入框外部时,我想要验证它(不确定使用哪个DOM事件)。问题是输入框“滞后”一个字符。
例如,如果用户输入“a”,那么它映射到的ngModel变量等于“”。当他们输入“ab”时,该变量等于“a”。 create-item.component.ts的部分代码:
export class CreateItem {
  public item: Item;

  constructor() {
    this.item = new Item();
  }

  onCheckItemInput() {
    // validate input on each keystroke
  }
}

create-item.component.html的输入字段

<input class="form-control" type="text" required [(ngModel)]="item.name"
  #spy pattern=".{3,255}" (input)="onCheckItemInput()">

我做错了什么?

你正在使用什么版本的Angular2? - Günter Zöchbauer
RC2。我们已经搞定了。 :) - DankestMemes
3个回答

2
blur事件是在用户使用输入元素后失去焦点时触发的。
例如:用户在输入框外单击。
<input class="form-control" type="text" required [(ngModel)]="item.name"
#spy pattern=".{3,255}" (blur)="onCheckItemInput()">

我已经创建了一个简单的Plunker来演示这个问题。 https://plnkr.co/edit/4wnanssu08WPRziMkh9d?p=preview

有时候我会匆忙行事。非常好的答案,满足了我所有的需求。 - DankestMemes

0

如果您想在用户单击输入字段外部时验证输入,则可以使用(change)事件,如果您想要验证每个按键,则可以使用(ngModelChange)事件。


0

如果想要在输入时进行更改,可以使用(keydown)

<input class="form-control" type="text" required [(ngModel)]="item.name"
  #spy pattern=".{3,255}" (keydown)="onCheckItemInput()">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接