如何使用ngModelChange
清除或编辑输入框?
我有一个傻瓜: https://embed.plnkr.co/oc1Q7lkEkXNxSag6Kcss/
我的角度通话位于template-driven-form.ts
这是我的HTML:
<h1>(ngModelChange) Example:</h1>
<p>
<label>Number:</label>
<input type="tel"
[(ngModel)]="expiration"
(ngModelChange)="onChange($event)"
name="expiration"
required>
</p>
这是角度代码:
expiration: string = '';
onChange(event) {
if (this.expiration) {
let expiration = this.expiration.toString();
expiration = expiration.replace(/[^0-9\\]/g, '');
if (expiration.length > 2) {
expiration += '\\';
}
this.expiration = expiration;
} else {
this.expiration = '';
}
}
我正在尝试实施信用卡的到期日期。
如果有人输入的数字不是数字,我应该忽略该输入。如果我得到超过3位数,我想添加\
。
但目前ngModelChange
的运作方式与我的预期无关。我输入了字母,它们被添加到输入框中。
我尝试更新模型expiration = ''
,但即使我有[(ngModel)]=expiration
,该字母也会保留在输入中。
编辑:我进行了更新以使用tel,因为\
不适用于输入类型number
。但是更新模型this.expiration = expiration
的代码行不起作用。
答案 0 :(得分:1)
Banana-in-a-box语法[(ngModel)]
是[ngModel]="expiration"
和(ngModelChange)="expiration=$event"
的简写语法。
我不建议同时使用两者。请尝试仅将[ngModel]
与(ngModelChange)
<强>更新强> 我做了很多黑客:)但你可以看看它: https://plnkr.co/edit/6e9UyKlhjaXVvZ0cEnlh?p=info
(keydown)
事件来过滤字母数字键盘事件在format
方法中,我逐步浏览字符并添加/
<input type="text"
name="mynubmer"
(keydown)="onKeydown($event)"
[ngModel]="format(expiration)"
(ngModelChange)="onChange($event)"
expiration="expiration"
required>
onKeydown($event) {
console.log($event)
// filter a-zA-z
if ($event.keyCode >= 65 && $event.keyCode <= 90) {
$event.preventDefault();
}
}
format(value) {
if (value) {
return value
.split('')
.map((character, index) => ((index+1) % 3 === 0)
? character + '/'
: character)
.join('');
}
return value;
}
onChange(event) {
this.expiration = event.split('').filter(char => char !== '/').join('');;
}
答案 1 :(得分:1)
可能是因为您需要在输入中添加属性“name”。 @Vinayak在此帖https://stackoverflow.com/a/48296665/7733724
中谈到了ngmodel和名称我在你的plnkr(template-driven-form.ts)中添加了name="expiration"
,并且事件已经开始起作用了。
对我来说,它正如你想要的那样工作:
import {Component} from '@angular/core'
import {FormsModule} from '@angular/forms'
@Component({
selector: 'template-driven-form',
template: `
<section>
<h1>(ngModelChange) Example:</h1>
<form #f="ngForm" (ngSubmit)="onSubmitTemplateBased()">
<p>
<label>Number:</label>
<input type="number"
[(ngModel)]="expiration"
(ngModelChange)="onChange($event)"
expiration="expiration"
required
name="expiration">
</p>
</form>
</section>
`
})
export class TemplateDrivenForm {
expiration: string;
onChange(event) {
if (this.expiration) {
let expiration = this.expiration.toString();
expiration = expiration.replace(/[^0-9\\]/g, '');
if (expiration.length > 2) {
expiration += '\\';
}
this.expiration= expiration;
} else {
this.expiration = '';
}
alert(this.expiration);
}
}