如何在Angular 5反应形式输入中使用管道

Dal*_*ley 33 angular-pipe angular angular-reactive-forms

我试图弄清楚如何在反应形式中使用管道,以便输入被强制为货币格式.我已经为此创建了自己的管道,我已经在代码的其他区域进行了测试,所以我知道它可以作为一个简单的管道工作.我的管道名称是'udpCurrency'

我在堆栈溢出上找到的最接近的答案就是这个:在Angular2-View中的INPUT元素中使用ngModel中的管道然而这在我的情况下不起作用,我怀疑它与我的表单是被动的事实有关

以下是所有相关代码:

模板

<form [formGroup]="myForm" #f="ngForm">
  <input class="form-control col-md-6" 
    formControlName="amount" 
    [ngModel]="f.value.amount | udpCurrency" 
    (ngModelChange)="f.value.amount=$event" 
    placeholder="Amount">
</form>
Run Code Online (Sandbox Code Playgroud)

组件

import { Component, OnInit, HostListener } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(
    private builder: FormBuilder
  ) {
    this.myForm = builder.group({
      amount: ['', Validators.required]
    });
  }    
}
Run Code Online (Sandbox Code Playgroud)

错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: '. Current value: 'undefined: undefined'
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 52

这是混合模板驱动形式和反应形式时可能发生的情况.你有两个绑定相互斗争.选择模板驱动或反应形式.如果你想进入反应路线,你可以使用[value]你的管道......

<form [formGroup]="myForm">
  <input 
    [value]="myForm.get('amount').value | udpCurrency"
    formControlName="amount" 
    placeholder="Amount">
</form>
Run Code Online (Sandbox Code Playgroud)

  • 这不能按预期方式工作,因为在管道转换之前触发了表单值更改。显示的值看起来正确,但是表单值将不同。 (6认同)
  • 这不起作用,因为在表单更新视图上的模型后,货币管道再次更新模型并最终尝试通过管道传输一个字符串值,这是我收到错误的地方。在下面查看我的解决方案以避免这种情况。 (5认同)
  • 最初可以使用,但是当您编辑值时,管道不会重新应用onblur。这是必须明确处理的吗? (3认同)
  • 这非常有用,谢谢.我在这个主题上找到了很多帖子,这些帖子都过于复杂,但这才有效. (2认同)

Dal*_*ley 9

我以为我可以进行这项工作,但事实证明,我错了(并接受了错误的答案)。我只是以一种对我更有效的新方式重述了我的逻辑,并回答了雅各布·罗伯茨在上述评论中的关注。这是我的新解决方案:

模板:

<form [formGroup]="myForm">
  <input formControlName="amount" placeholder="Amount">
</form>
Run Code Online (Sandbox Code Playgroud)

组件:

import { Component, OnInit, HostListener } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UdpCurrencyMaskPipe } from '../../../_helpers/udp-currency-mask.pipe';

export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(
    private builder: FormBuilder,
    private currencyMask: UdpCurrencyMaskPipe,
  ) {
    this.myForm = builder.group({
      amount: ['', Validators.required]
    });

    this.myForm.valueChanges.subscribe(val => {
      if (typeof val.amount === 'string') {
        const maskedVal = this.currencyMask.transform(val.amount);
        if (val.amount !== maskedVal) {
          this.myForm.patchValue({amount: maskedVal});
        }
      }
    });
  }    
}
Run Code Online (Sandbox Code Playgroud)

管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'udpCurrencyMask'
})
export class UdpCurrencyMaskPipe implements PipeTransform {
    amount: any;

    transform(value: any, args?: any): any {

        let amount = String(value);

        const beforePoint = amount.split('.')[0];
        let integers = '';
        if (typeof beforePoint !== 'undefined') {
            integers = beforePoint.replace(/\D+/g, '');
        }
        const afterPoint = amount.split('.')[1];
        let decimals = '';
        if (typeof afterPoint !== 'undefined') {
            decimals = afterPoint.replace(/\D+/g, '');
        }
        if (decimals.length > 2) {
            decimals = decimals.slice(0, 2);
        }
        amount = integers;
        if (typeof afterPoint === 'string') {
            amount += '.';
        }
        if (decimals.length > 0) {
            amount += decimals;
        }

        return amount;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我在这里学到了几件事。一个是雅各布所说的正确的说法,另一种方法只是最初起作用,但是当值更改时不会更新。需要注意的另一个非常重要的事情是,与视图管道相比,我需要一种完全不同类型的蒙版管道。例如,视图中的管道可能会将此值“ 100”并将其转换为“ $ 100.00”,但是您不希望在键入该值时进行该转换,而只希望在完成键入后进行该转换。因此,我创建了我的货币掩码管道,该管道仅删除了非数字并将十进制限制在两个位置。


Dre*_*rew 6

我打算编写一个自定义控件,但发现从 FormControl 类中覆盖“onChange”ngModelChange更容易。这emitViewToModelChange: false在您的更新逻辑期间至关重要,以避免重复发生更改事件循环。所有通向货币的管道都发生在组件中,您不必担心会出现控制台错误。

<input matInput placeholder="Amount" 
  (ngModelChange)="onChange($event)" formControlName="amount" />
Run Code Online (Sandbox Code Playgroud)
@Component({
  providers: [CurrencyPipe]
})
export class MyComponent {
  form = new FormGroup({
    amount: new FormControl('', { validators: Validators.required, updateOn: 'blur' })
  });

  constructor(private currPipe:CurrencyPipe) {}

  onChange(value:string) {
    const ctrl = this.form.get('amount') as FormControl;

    if(isNaN(<any>value.charAt(0))) {
      const val = coerceNumberProperty(value.slice(1, value.length));
      ctrl.setValue(this.currPipe.transform(val), { emitEvent: false, emitViewToModelChange: false });
    } else {
      ctrl.setValue(this.currPipe.transform(value), { emitEvent: false, emitViewToModelChange: false });
    }
  }

  onSubmit() {
    const rawValue = this.form.get('amount').value;

    // if you need to strip the '$' from your input's value when you save data
    const value = rawValue.slice(1, rawValue.length);

    // do whatever you need to with your value
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 当我 3 1/2 年前写的时候,我的答案是针对 Angular v5 的。它肯定适用于当时,但正如您所指出的,这不是现在最好的解决方案。 (2认同)