我已经声明了一种将大数字分成三位数组的格式,并像这样经常使用它。
<div>Huge number: {{ i_am_huge | make_threesome }}</div>
现在,有一个对相应功能的请求,但在像这样的输入控件中实现。
<input id="numeroUno"
type="text">
我能想到的方法是听输入内容,并对每个键执行框内容的重新格式化,如下所示。
<input id="numeroUno"
type="text"
(keyup)="formatify">
然而,虽然这种方法可行,但我不停地想知道它是否有太多的 Q&D,所以在我围绕这个范例构建一个完整的控制动物群之前,我想获得更多信息。
通常的谷歌搜索并没有给我带来太多信息。然而,如果需求的性质相当不寻常,可能很难找到。
此时的假设是输入控制不应该以这种方式使用,这解释了我的方法的笨拙。
最佳答案
使用指令。在 stackblitz您可以看到如何工作。
该指令将不带空格的字符串存储在变量“value”中。每次发生更改(我使用@HotListener(input))获取光标的位置,获取元素的值,删除空格,格式化数字并将光标放在该位置
@Directive({ selector: "[testPipe]" })
export class TestPipe implements OnInit {
private el: HTMLInputElement;
private value: any;
constructor(@Optional() private ngControl:NgControl,
private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener("input", ["$event.target.value"])
onInput() {
let pos = this.el.selectionStart; //get the position of the cursor
this.value = this.el.value.replace(/ /gi, ""); //store the value without spaces
if (this.value.length%3==1) //If we must add an extra space
pos++;
//Yes, it's a "bizarro" way to separate in group of three
this.el.value=this.value.match(/(.+?)(?=(.{3})+(?!.)|$)/g).join(' ');
//this.el.value=this.value.match(/(\d+?)(?=(\d{3})+(?!\d)|$)/g).join(' ');
//Finally give the position of cursor
this.el.selectionStart = this.el.selectionEnd = pos;
if (this.ngControl)
this.ngControl.control.setValue(this.el.value,{emit:false})
}
ngOnInit()
{
this.value = this.el.value.replace(/ /gi, "");
this.el.value=this.value.match(/(.+?)(?=(.{3})+(?!.)|$)/g).join(' ');
// this.el.value=this.value.match(/(\d+?)(?=(\d{3})+(?!\d)|$)/g).join(' ');
if (this.ngControl)
this.ngControl.control.setValue(this.el.value,{emit:false})
}
}
更新 我在构造函数中添加了 @Optional() ngControl:NgControl,因此,如果该指令应用于 ngControl(输入属于 formGroup 或具有 [(ngModel)],也改变值
关于html - 编辑时可以在文本框控件内使用 Angular 的管道格式化程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086460/