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

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

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


当前回答

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

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

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

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

其他回答

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

获取一个FormGroup的所有更改:

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

获取特定字段的更改:

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

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

在.html文件中:

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

在.ts文件中:

onSearchChange(searchValue: string): void {  
  console.log(searchValue);
}
<input type="text" [ngModel]="mymodel" (keypress)="mymodel=$event.target.value"/>
{{mymodel}}

更新

https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event

警告:由于此事件已弃用,您应该使用beforeinput或keydown代替。

你要找的是

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

然后通过访问绑定this对数据做任何你想做的事情。我的模型在你的。ts文件。

这个问题有多种答案。 然而,如果你想用另一种方式,特别是在你对change事件采取任何行动之前添加一些延迟,那么你可以使用带有angular形式valuechanges()的debounceTime()方法。这段代码需要添加在ngOnInit()钩子或创建一个单独的方法,并从ngOnInit()调用它。

  ngOnInit(): void {
    this.formNameInputChange();
  }

  formNameInputChange(){
    const name = this.homeForm.get('name'); // Form Control Name
    name?.valueChanges.pipe(debounceTime(1000)).subscribe(value => {
      alert(value);
    });
  }
  // this is reactive way..
  homeForm = this.fb.group({
    name:['']
  });