Angular:添加斜杠" /"在日期字段的输入类型文本中

时间:2017-12-13 22:12:35

标签: html angular typescript angular2-template angular2-forms

大家好我是angular-js的新手, 我想在Input type = text。

中添加斜杠

我不想使用任何软件包,例如angular-ui或输入类型Date。

我想添加/,因为用户输入的日期就像是在两位数之后,然后在第五位12/12/2012之后输入mm/dd/yyyy格式。 我试过以下代码。请帮我,我错了。

@component({
selector: 'exp-basic-identity',
  template: `
    <input placeholder="Date of Birth(MM/DD/YYYY)"
                           ([ngModel])="formGroup.controls['dob'].value"
                                           formControlName="dob"
                                           (input) = "onKey($event.target.value)"
                                           [type]="'text'"
                                           [animatePlaceholder]="true" i18n>'


export class ExpBasicIdentityComponent implements OnInit {
  public formGroup: FormGroup;
 key: string;
  event: KeyboardEvent;
 onKey(event: KeyboardEvent) {
        let DobVal = this.formGroup.controls['dob'].value;
        if (DobVal.length === 2 || DobVal.length === 5 ) {
            DobVal = DobVal + '/';
        }

    }
}

我没有在angular.js中找到任何资源 我得到的只是在jquery或javascript中。 所以试图以这种方式实施。

现在我正在接受&#34; /&#34;当我在调试时看到image of slash added - debugging

如何在用户输入时自动添加斜杠? 请帮帮我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

  

现在我正在接受&#34; /&#34;当我在调试中看到

这是因为您处于A点,这意味着点B处的代码已经执行。 /来自您在B

点编写的代码

enter image description here

答案 1 :(得分:1)

我使用以下代码解决了。 感谢@LLai

 onKey(event: KeyboardEvent) {
        let DobVal = this.formGroup.controls['dob'].value;
        if (DobVal.length === 2 || DobVal.length === 5 ) {
            this.formGroup.controls['dob'].setValue(DobVal + '/');
        }
    }

当我使用BACKSPACE清除字母时,在/之后,它没有清除。有什么方法可以避免这种情况吗?

Latest Output

有人可以帮忙解决这个问题吗? 提前谢谢。

相关问题