gpt4 book ai didi

html - 编辑时可以在文本框控件内使用 Angular 的管道格式化程序吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:37 27 4
gpt4 key购买 nike

我已经声明了一种格式,用于将大数字分成三位数字组并像这样经常使用它。

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com