如何在Angular响应式表单中设置输入值的货币格式?

4

当用户移动到另一个字段时,我希望在金额字段中应用货币格式,然后金额值将转换为货币格式,并且当控件聚焦时,货币格式将被删除。

我已经尝试使用hostlistner在自定义指令中绑定onblur和onfocus事件,但是我想不创建自定义指令就能实现吗?

这是我的HTML代码。

<input type="text" formControlName="amount" />

On the amount field I want to set currency format without creating custom directive.

不创建自定义指令,这是否可能?


1
请发布您的组件和HTML代码以便更好地理解和帮助您。 - User3250
我已经编辑了我的问题,请检查。 - Vipin
这还不够,还需要在组件中添加你尝试过的代码。 - User3250
你可以使用管道来处理货币。通过使用一个布尔变量来保存字段的状态,货币将根据此状态显示/隐藏。你可以从这里阅读文档 https://angular.io/api/common/CurrencyPipe 。如果我理解了你的问题 - Sorin Veștemean
如果你想避免编写指令(或为某些掩码输入行为安装npm库),那么我能想到的唯一解决方案是在表单组中有两个表单控件,一个用于格式化,一个用于原始输入。然后在模板中进行一些值同步和一些隐藏/显示操作。但是当你考虑这个问题时,实际上应该由指令来控制行为,因为如果你碰巧需要在另一个组件中使用相同的模式,这将只是一个即插即用的解决方案。可能编写指令所花费的时间会相似。 - user776686
2个回答

1

Angular从其@angular/common API中引入了Pipe的概念。

专门为货币实现的API名称是CurrencyPipe。请单击附加的链接以获取详细说明。

回答你的问题,

您可以直接在Angular组件中使用CurrencyPipe。按照以下步骤操作即可使其正常工作。

  1. Register CurrencyPipe to your respective angular(NgModule) Module under Providers. Please note that it should be imported from @angular/common

    @NgModule({
      declarations: [],
      imports: [],
      providers:[CurrencyPipe]
    })
  2. Inject CurrencyPipe instance to your Angular(Ng) Component and use the method transform to convert the amount in target currency format.

    @Component({
      selector: 'selector-name',
      templateUrl: './design.html',
      styleUrls: ['./design.scss']
    })
    export class YourComponent implements OnInit {
        formGroup: FormGroup;
        constructor(private currencyPipe: currencyPipe, private formBuilder: FormBuilder){
        }
        ngOnInit() {
            const amount = 25.00;
            const amountInCurrencyFormated = this.currencyPipe.transform(amount);
            this.formGroup = this.formBuilder.group({
                amount: amountInCurrencyFormated
            });
        }
    }
您期望的输出是:

您的期望输出: $25.00


0
可能不一定是你想要的,但对其他人可能有用。你可以尝试在两个输入之间切换。
<input type="text" id="amount" formControlName="amount"(blur)="hideAmountInput()">

<input type="text" id="hidden-amount" (focus)="showAmountInput()"
 style="display: none;" [value]="form.controls['amount'].value | currency:'$' " >

 hideAmountInput() {
    (document.getElementById('hidden-amount') as HTMLInputElement).style.display = 'block';
    let input = document.getElementById('amount') as HTMLInputElement;
    input.style.display = 'none';
  }

  showAmountInput() {
    (document.getElementById('hidden-amount') as HTMLInputElement).style.display = 'none';
    let input = document.getElementById('amount') as HTMLInputElement;
    input.style.display = 'block';
    input.focus();
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接