【问题标题】:Angular 5 Pipe, {updateOn:'blur'} not updating model as expectedAngular 5 Pipe,{updateOn:'blur'} 未按预期更新模型
【发布时间】:2018-12-09 02:48:25
【问题描述】:

我在 Angular 5 中创建了一个自定义管道,用于更新模糊时输入字段的显示。

输入字段的值被转换并显示,但模型的值没有正确更新。这是我所期待的功能,有没有办法用管道实现这个功能?

Stackblitz - Link to Sample Code

重现问题的步骤。

删除现有值并输入任意数字,然后在字段外单击。 (例如:242235.34234)

输入值和模型值不匹配。

HTML 代码:

<h1>Currency Pipe</h1>

<div>
  Input:
  <input type="text" [ngModel]="inputValue | currency" name="inputValue"
    [ngModelOptions]="{updateOn:'blur'}" (ngModelChange)="inputValue=$event"/>
</div>

<div>{{ inputValue }}</div>

角管:

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

@Pipe({
  name: 'currency'
})
export class CurrencyPipe implements PipeTransform {

  private format = { precision: 2, thousand: ',', decimal: '.' };

  transform(value: string): any {

    let formattedValue = accounting.unformat(value);
    return accounting.formatNumber(formattedValue, this.format);
  }

}

【问题讨论】:

  • stackblitz 的共享链接已损坏。你能纠正一下吗?
  • 感谢指出,更正。

标签: angular angular-pipe


【解决方案1】:

您要为输入添加管道,而不是为输出添加管道? {{ 输入值 |货币 }}

【讨论】:

  • 感谢您的替代方案,但我担心的是,没有将管道添加到输出;模型值应自动更新。提供给输入的货币管道应在模糊时更新模型的值。输入值将绑定到模型值对吗?
  • 不,管道不会更新原始值。它将值通过管道传输到不同的输出。根据您的代码,它是管道的全部要点。你不希望它是小数点后 2 位,否则计算可能会出错
  • 事实上,我想说,倒过来。不要管输入,只管输出。
  • 不,它会更新模型,但不会立即更新。请尝试以下步骤: 1. 清除该字段并输入一个大值。例如:12345 2. 编辑值并点击外部,模型会相应更新格式化值。
  • 你在想getter setter。管道不应更新该值。调试inputValue,你会发现值没有改变。
【解决方案2】:

正如我之前所说,您不应该使用管道来改变值。相反,请尝试使用 getter/setter。

import { Component } from '@angular/core';
import * as accounting from 'accounting';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private $inputValue;
  private format = { precision: 2, thousand: ',', decimal: '.' };

  set inputValue(value){
    let formattedValue = accounting.unformat(value);
    this.$inputValue = accounting.formatNumber(formattedValue, this.format);
  } 

  get inputValue(){ return this.$inputValue; }
}

并从 html 中删除所有管道内容。

【讨论】:

  • 谢谢你,我只有一个字段很好。在我的应用程序中,我现在有许多字段,跨越许多页面。有什么办法可以将其用作可重用组件?将其转换为指令有帮助吗?
  • 这取决于你。 Angular 可以随心所欲地简单或复杂。拥有一百万个 getter setter 可能看起来不太好,但对我来说很容易理解。但每个人都有自己的
  • 好的,非常感谢。将研究可能性并进行更新。 :)
猜你喜欢
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2018-08-08
  • 1970-01-01
相关资源
最近更新 更多