我提前为我的英语道歉并希望让自己明白。
我有一个表单,我希望用户在输入中添加日期,我自己添加的/
。代码工作得很好,因为它在console
中正确显示。但是不可能在输入(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, '$1/')
}
})
}
这里的模板:
<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>
我希望我能够解释我的问题并且你能够理解我。感谢那些试图解决这个小问题的人。
对于反应式表单,您不能像更改方式一样更新值。代替
res.replace(/(..)/g, '$1/')
应该:
this.petForm.controls.birthday.setValue(res.replace(/(..)/g, '$1/'), {
emitEvent: false
});
注意setValue
第二个参数,我通过emitEvent: false
不触发价值变化事件。否则你的代码可能会无限循环。
删除订阅并尝试此操作: HTML:
<input .... #birthday (input)="birthday.value=changeValue(birthday.value)" ....>
打字稿:
changeValue(value){
const resLength = value.length;
if(resLength < 6 ) {
return value.replace(/(..)/g, '$1/');
}
return value;
}