javascript - 如何在反应式表单字段中使用管道?
问题描述
我在angular6中使用反应形式。表单字段包含十进制值,但我需要将这些十进制值转换为整数值。
重要提示:不应丢失准确性。只有在 TEMPLATE 用户才能看到整数值。但是在组件(又名控制器)中,值应该是小数。
我的尝试:
模板:
<form [formGroup]="fg">
<input formControlName="{{name1 | testPipe}}">
<input formControlName="{{name2 | testPipe}}">
<input formControlName="{{name3 | testPipe}}">
</form>
组件(又名控制器):
fg: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.fg = this.fb.group({
name1: this.fb.control(1.3),
name2: this.fb.control(33.34),
name3: this.fb.control(3.5),
})
}
管道:
@Pipe({
name: 'testPipe'
})
export class TestPipe implements PipeTransform {
transform(value: string): any {
return Math.round(+value);
}
}
解决方案
我认为您需要一个指令,而不是管道。在指令中,您侦听 onBlur 和 onFocus 事件以存储值并显示四舍五入的值。有些喜欢
@Directive({ selector: "[testPipe]" })
export class TestPipe implements OnInit {
private el: HTMLInputElement;
private value: any; //<--here you store the "real value"
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener("focus", ["$event.target.value"])
onFocus() {
this.el.value = this.value; // on focus return the value stored
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) { //in blur
this.value = value; //store the real value
this.el.value = '' + Math.round(+value); //change the value you show
}
ngOnInit() //At init
{
this.value = this.el.value;
this.el.value = '' + Math.round(+this.value);
}
你用喜欢
<form [formGroup]="fg">
<input formControlName="name1" testPipe >
<input formControlName="name2" testPipe>
<input formControlName="name3" testPipe>
</form>
{{fg?.value |json}}
你可以看到正在工作的 stackblitz
注意:您想要管理管道和创建 formGroup 的方式非常奇怪,请参阅代码
推荐阅读
- kubernetes - 为角色绑定修补命名空间和更改资源类型
- eclipse - Liferay 为多个 portlet 创建自定义 PanelCategory
- highcharts - Highcharts MapBubble - 是否可以使用数据模块加载数据?
- c - libnfc6 未检测到 Revolut Visa 借记卡
- flutter - 如何在 sqflite 颤振中使用 propper 更新
- python - 如何解决这个 Python AttributeError: module 'matplotlib' has no attribute 'get_data_path' (in JupyterLab 3.0>=)
- javascript - 使用 async/await 承诺在“并行”中运行 for 循环
- react-native - npm install 和 codepush:上传的包没有发布,因为它与指定部署的当前发布的内容相同
- react-native - 反应原生灯箱没有缩放
- acumatica - 使用 Acumatica 中的参数运行 EXE