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

<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);
}

其他回答

处理这种情况的另一种方法是使用formControl并在组件初始化时订阅它的valueChanges,这将允许您使用rxjs操作符来执行高级要求,如执行http请求,应用debounce直到用户写完一个句子,获取最后一个值并省略前一个值,等等。

import {Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

@Component({
  selector: 'some-selector',
  template: `
    <input type="text" [formControl]="searchControl" placeholder="search">
  `
})
export class SomeComponent implements OnInit {
  private searchControl: FormControl;
  private debounce: number = 400;

  ngOnInit() {
    this.searchControl = new FormControl('');
    this.searchControl.valueChanges
      .pipe(debounceTime(this.debounce), distinctUntilChanged())
      .subscribe(query => {
        console.log(query);
      });
  }
}
<input type="text" (keypress)="myMethod(myInput.value)" #myInput />

归档.ts

myMethod(value:string){
...
...
}

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

在.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" (keyup)="valuechange()" />
{{mymodel}}

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

<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代替。