在输入中创建事件 (angular 4+)
Create an event in an input (angular 4+)
我提前为我的英语道歉,希望能让我明白。
我有一个表格,我希望用户在输入中添加一个日期,/
是我自己添加的。该代码运行良好,因为它在 console
中正确显示。但是不可能在 input(type = text).
中重现这一点
这里是 component.ts:
ngOnInit() {
this.changes()
}
changes() {
this.petForm.controls.birthday.valueChanges
.subscribe(res => {
const resLength = res.length
if(resLength < 6 ) {
res.replace(/(..)/g, '/')
}
})
}
在 console
没问题这是它的样子:
这里是模板:
<div class="form-group">
<label for="birthday" class="size0">{{ 'PARTNER.bday_placeholder' |
translate}} *</label>
<input
class="input--default input__signup__default"
formControlName="birthday"
type="text"
placeholder="{{'PARTNER.bday_placeholder' | translate}} *"
required>
</div>
我希望我能够解释我的问题并且你能够理解我。感谢那些试图解决这个小问题的人。
删除订阅并试试这个:
HTML:
<input .... #birthday (input)="birthday.value=changeValue(birthday.value)" ....>
打字稿:
changeValue(value){
const resLength = value.length;
if(resLength < 6 ) {
return value.replace(/(..)/g, '/');
}
return value;
}
对于反应式表单,您不能像您那样只更新值。
而不是
res.replace(/(..)/g, '/')
应该是:
this.petForm.controls.birthday.setValue(res.replace(/(..)/g, '/'), {
emitEvent: false
});
注意 setValue
第二个参数,我传入 emitEvent: false
不触发值更改事件。否则您的代码可能会无限循环。
我提前为我的英语道歉,希望能让我明白。
我有一个表格,我希望用户在输入中添加一个日期,/
是我自己添加的。该代码运行良好,因为它在 console
中正确显示。但是不可能在 input(type = text).
这里是 component.ts:
ngOnInit() {
this.changes()
}
changes() {
this.petForm.controls.birthday.valueChanges
.subscribe(res => {
const resLength = res.length
if(resLength < 6 ) {
res.replace(/(..)/g, '/')
}
})
}
在 console
没问题这是它的样子:
这里是模板:
<div class="form-group">
<label for="birthday" class="size0">{{ 'PARTNER.bday_placeholder' |
translate}} *</label>
<input
class="input--default input__signup__default"
formControlName="birthday"
type="text"
placeholder="{{'PARTNER.bday_placeholder' | translate}} *"
required>
</div>
我希望我能够解释我的问题并且你能够理解我。感谢那些试图解决这个小问题的人。
删除订阅并试试这个:
HTML:
<input .... #birthday (input)="birthday.value=changeValue(birthday.value)" ....>
打字稿:
changeValue(value){
const resLength = value.length;
if(resLength < 6 ) {
return value.replace(/(..)/g, '/');
}
return value;
}
对于反应式表单,您不能像您那样只更新值。 而不是
res.replace(/(..)/g, '/')
应该是:
this.petForm.controls.birthday.setValue(res.replace(/(..)/g, '/'), {
emitEvent: false
});
注意 setValue
第二个参数,我传入 emitEvent: false
不触发值更改事件。否则您的代码可能会无限循环。