gpt4 book ai didi

angular - 如何以 Angular react 形式设置输入值的货币格式?

转载 作者:行者123 更新时间:2023-12-04 13:43:36 25 4
gpt4 key购买 nike

当用户移动到另一个字段时,我想在我的金额字段中应用货币格式,然后金额值将转换为货币格式,当控制焦点时,货币格式将被删除。

我曾尝试使用 hoSTListner 在自定义指令中绑定(bind)事件 onblur 和 onfocus 事件,但我不想创建自定义指令?

这是我的 HTML 代码。

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

在金额字段上,我想在不创建自定义指令的情况下设置货币格式。

是否可以不创建自定义指令?

最佳答案

Angular 提出 管道 来自它的概念 @angular/common
应用程序接口(interface)。

The name of the API which is specially implemented for Currency is CurrencyPipe. Please click on the link which is attached for detailed description.



回答你的问题,

您可以将 CurrencyPipe 直接用于 Angular 组件。请按照以下步骤操作。
  • 注册 CurrencyPipe 到您各自的 Angular (NgModule) Module Providers .请注意,它应该从 导入@angular/common
    @NgModule({
    declarations: [],
    imports: [],
    providers:[CurrencyPipe]
    })
  • 将 CurrencyPipe 实例注入(inject)您的 Angular(Ng) Component 并使用方法 transform 以目标货币格式转换金额。
    @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 美元

    关于angular - 如何以 Angular react 形式设置输入值的货币格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111906/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com