一个小小的输入框Input
<div>
testNameInput
<input type="text" nz-input [(ngModel)]="testNameInput" (input)="testNameChange(testNameInput)">
testNameEventInput
<input type="text" nz-input [(ngModel)]="testNameEventInput" (input)="testNameEventChange($event.target.value)">
testNameModelInput
<input type="text" nz-input [(ngModel)]="testNameModelInput" (ngModelChange)="testNameModelChange(testNameModelInput)">
testNameControl
<input type="text" nz-input [formControl]="testNameControl" name="testNameControl">
</div>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styles: ['']
})
export class InputComponent implements OnInit {
constructor() { }
testNameInput = '';
testNameEventInput = '';
testNameModelInput = '';
testNameControl: FormControl = new FormControl('');
ngOnInit() {
// 响应式表单中的change事件
this.testNameControl.valueChanges.subscribe(values=>{
console.log('values == testNameControl', values);
})
}
// 原生change事件,传入model
testNameChange(value){
console.log('values == testNameInput', value);
}
// 原生change事件,传入$event.target
testNameEventChange(value){
console.log('values == testNameEventInput', value);
}
// 模板驱动表单中的change事件
testNameModelChange(value){
console.log('values == testNameModelInput', value);
}
}
中文状态下输入 123?你好1
结果截图
结果分析
在英文状态下输入,这几个方法获取的数字都一致,但在中文状态下获取的就有所区别了
- testNameInput
从结果显示可以看出,在中文状态下输入’?哈喽’以及按空格的时候,获取的model值并未更新,当又输入了1的时候,才进行了更新
- testNameEventInput
在输入每一个字符的时候,都能获取到,连中文输入过程中的字母也呈现了出来
- testNameModelInput 和 testNameControl
这两个一致,都是调用angular-form给的监听方法,输出一致,中文状态下,特殊字符随时显示,中文输入过程不显示,只显示最后转换到输入框中的汉字。同时也会过滤掉中文输入过程未转化之前的事件监听。
testNameModelInput
是模板驱动表单中建议使用的监听方法
testNameControl
是响应式表单中建议使用的监听方法
总结
四种监听方法,可以根据具体的场景来选择使用。正常场景建议使用angular-form提供的方法。