在 Angular2 的输入值之前添加加号 "+"



这个问题听起来很简单,但我可以找到任何明确的解决方案。

我有电话号码的自定义输入字段(我正在使用反应式表单方法(。目的是在输入值之前始终有一个加号。

要求:

  • 包括加号在内的整个输入值应该是可选的(即在输入之前添加 span-s 或带有加号的div-s 的 hack 是不可接受的(
  • 如果输入值为空 - 可以删除加号,否则如果我们添加数字,则应将其添加到输入值的开头
  • 使用第三方库是不可接受的
  • 使用新值(例如"123456"(修补表单控件时 - 它还应该在前面添加加号

我们如何在 Angular2 项目中实现这个逻辑?

这是一个可以绑定到input(change)事件的函数:

processInput(inputVal: string = null) {
if (!inputVal) {
inputVal = this.myForm.get('myInput').value; // since you're using reactive forms
}
if (inputVal === '') {
// Do nothing
} else if (inputVal.match(/^d*$/)) {
if (!inputVal.includes('+')) {
inputVal = '+' + inputVal;
}
}
// Then patch your 'myInput' value in your form with 'inputVal'
this.myForm.patchValue({ 'myInput': inputVal });
}
safePatchMyInput(value: string) {
this.processInput(value);
}

当(且仅当(输入字符串包含纯数字时,此实现将添加一个加号。它还允许您完全清空输入(包括加号(。

编辑:添加safePatchMyInput方法将允许您手动修补该输入,并且仍然使用与上一个功能相同的输入处理。(这意味着将默认参数添加到上一个函数中(

绑定到输入上的(change)事件将如下所示:

<input (change)="processInput()"/>

编辑 2

这是一个更新的解决方案,即使输入是通过patchValue手动设置的,也可以与FormControl.registerOnChange一起使用来处理输入。

角度组件:

myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
'myInput': new FormControl('')
})
}
ngOnInit() {
const myInput = this.myForm.get('myInput') as FormControl;
myInput.registerOnChange(this.processInput);
}
processInput = () => {
let inputVal = this.myForm.get('myInput').value;
if (inputVal === '') {
// Do nothing
} else if (inputVal.match(/^d*$/)) {
if (!inputVal.includes('+')) {
inputVal = '+' + inputVal;
// Then patch your 'myInput' value in your form with 'inputVal'
this.myForm.patchValue({ 'myInput': inputVal });
}
}
}

模板:

<form [formGroup]="myForm">
<input formControlName="myInput" (input)="processInput()"/>
</form>

堆栈闪电战,供参考。

我快速将一些东西放在一起,代码需要重构,但本质上它完成了您的要求。您可以在 formControl 上订阅 valueChanges 事件,在这里您可以对生成所需结果所需的值进行所有修改。链接到堆栈闪电战:https://stackblitz.com/edit/angular-9mubgr

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
name = 'Angular';
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
'myInput': new FormControl('')
})
}

ngOnInit() {
this.myForm.get('myInput').valueChanges.subscribe((inputValue) => {
if(inputValue === this.myForm.get('myInput')) {
return;
}
if(inputValue.length === 0) {
return;
}
if(inputValue.legth !== 0 && inputValue.slice(0,1) !== '+') {
this.myForm.get('myInput').setValue('+' + this.myForm.get('myInput').value);
}
});
}
patch() {
this.myForm.patchValue({ 'myInput': '123' })
}
}

最新更新