首页 > 解决方案 > 如何在反应式表单字段中使用管道?

问题描述

我在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);
  }
}

标签: javascriptangular

解决方案


我认为您需要一个指令,而不是管道。在指令中,您侦听 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 的方式非常奇怪,请参阅代码


推荐阅读