在输入中创建事件(角度4+)

问题描述 投票:0回答:2

我提前为我的英语道歉并希望让自己明白。

我有一个表单,我希望用户在输入中添加日期,我自己添加的/。代码工作得很好,因为它在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/')
  }
})
}

console这里没有问题是它的样子: enter image description here

这里的模板:

<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>

我希望我能够解释我的问题并且你能够理解我。感谢那些试图解决这个小问题的人。

angular angular4-forms angular-template
2个回答
1
投票

对于反应式表单,您不能像更改方式一样更新值。代替

res.replace(/(..)/g, '$1/')

应该:

this.petForm.controls.birthday.setValue(res.replace(/(..)/g, '$1/'), {
      emitEvent: false
    });

注意setValue第二个参数,我通过emitEvent: false不触发价值变化事件。否则你的代码可能会无限循环。

示例网址:https://stackblitz.com/edit/angular-amqta3


1
投票

删除订阅并尝试此操作: 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.