更改事件仅在输入的焦点发生更改后才被调用。我怎样才能使事件在每次按键时触发?

<input type="text" [(ngModel)]="mymodel" (change)="valuechange($event)" />
{{mymodel}}

第二次绑定在每个按键上都发生变化。


当前回答

我只是使用事件输入,它工作得很好如下:

在.html文件中:

<input type="text" class="form-control" (input)="onSearchChange($event.target.value)">

在.ts文件中:

onSearchChange(searchValue: string): void {  
  console.log(searchValue);
}

其他回答

对于响应式表单,您可以订阅对所有字段或仅对特定字段所做的更改。

获取一个FormGroup的所有更改:

this.orderForm.valueChanges.subscribe(value => {
    console.dir(value);
});

获取特定字段的更改:

this.orderForm.get('orderPriority').valueChanges.subscribe(value => {
    console.log(value);
  });

在我的案例中,解决方案是:

[ngModel]="X?.Y" (ngModelChange)="X.Y=$event"

我用下面的代码在Angular 11中解决了这个问题:

<input type="number" min="0" max="50" [value]="input.to" name="to"
        (input)="input.to=$event.target.value; experienceToAndFrom()">

并且,experienceToAndFrom()是我的组件中的一个方法。

PS:我尝试了以上所有的解决方案,但都不奏效。

通过将[(x)]语法分解成两部分来使用ngModelChange,即属性绑定和事件绑定:

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
  mymodel = newValue;
  console.log(newValue)
}

它也适用于退格键。

我一直在使用keyup在一个数字字段,但今天我注意到在chrome的输入有上升/下降按钮来增加/减少的值,这是不被keyup识别。

我的解决方案是使用keyup和更改一起:

(keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"

初步测试表明,这工作良好,将在进一步测试后,如果发现任何错误。