更改事件仅在输入的焦点发生更改后才被调用。我怎样才能使事件在每次按键时触发?
<input type="text" [(ngModel)]="mymodel" (change)="valuechange($event)" />
{{mymodel}}
第二次绑定在每个按键上都发生变化。
更改事件仅在输入的焦点发生更改后才被调用。我怎样才能使事件在每次按键时触发?
<input type="text" [(ngModel)]="mymodel" (change)="valuechange($event)" />
{{mymodel}}
第二次绑定在每个按键上都发生变化。
当前回答
<input type="text" (keypress)="myMethod(myInput.value)" #myInput />
归档.ts
myMethod(value:string){
...
...
}
其他回答
通过将[(x)]语法分解成两部分来使用ngModelChange,即属性绑定和事件绑定:
<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
mymodel = newValue;
console.log(newValue)
}
它也适用于退格键。
我只是使用事件输入,它工作得很好如下:
在.html文件中:
<input type="text" class="form-control" (input)="onSearchChange($event.target.value)">
在.ts文件中:
onSearchChange(searchValue: string): void {
console.log(searchValue);
}
我用下面的代码在Angular 11中解决了这个问题:
<input type="number" min="0" max="50" [value]="input.to" name="to"
(input)="input.to=$event.target.value; experienceToAndFrom()">
并且,experienceToAndFrom()是我的组件中的一个方法。
PS:我尝试了以上所有的解决方案,但都不奏效。
处理这种情况的另一种方法是使用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);
});
}
}
这个问题有多种答案。 然而,如果你想用另一种方式,特别是在你对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:['']
});