【问题标题】:Get value from input with currency mask in Angular2在Angular2中使用货币掩码从输入中获取价值
【发布时间】:2017-11-30 05:47:25
【问题描述】:

我在表单内的输入中使用了maskMoney jquery 插件。当我想从那些输入字段中获取数据时,它是空的!

这是我的 MaskMoney 指令:

import {Directive, ElementRef} from "@angular/core";
declare var $: any;

@Directive({
  selector: '[money]'
})
export class CurrencyMaskDirective {
  constructor(public el: ElementRef) {
    let native = el.nativeElement;
    $(native).maskMoney({
      suffix: " $",
      thousands: '،',
      decimal: '',
      precision: 3,
      affixesStay: false
    });
  }
}

这是我的表格:

<form role="form" #f="ngForm" (ngSubmit)="addcharge(f)" novalidate>
   <input type="text" name="value" #value="ngModel" ngModel money>
</form>

// in ts file
addcharge(g) {
   console.log(g.value);
}

当我记录控制台中的值是空的!如何正确地从该输入中获取价值?

谢谢。

【问题讨论】:

    标签: jquery angular


    【解决方案1】:

    我认为您必须像下面的代码一样在 html 视图中分配 ngModel。

    <form role="form" #f="ngForm" (ngSubmit)="addcharge(f)" novalidate>
       <input type="text" name="value" #value="ngModel" [(ngModel)]="moneyValue" money>
    </form>
    
    // in ts file
    moneyValue: string = null;
    addcharge(g) {
       console.log(this.moneyValue);
    }
    

    【讨论】:

    • 您要登录this.moneyValue 吗?
    【解决方案2】:

    你不需要一个单一输入的表单我觉得这应该可以正常工作

    <div>
      <input type="text" name="value" #titleInput money>
      <button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
    </div>
    
    
      addTodo(title:string) {
        console.log(title);
      }
    

    如果您需要查看反应式或模板驱动的表单,您可以查看@此页面以获取示例

    https://rahulrsingh09.github.io/AngularConcepts/#/reactive

    https://rahulrsingh09.github.io/AngularConcepts/#/template

    更新

    检查这个 Plunker 链接

    https://plnkr.co/edit/oicEbx5HQj3T208GCuU7?p=preview

    【讨论】:

    • 我在这个问题中只添加了一个输入,我在主表单中有更多输入。
    • 请查看链接代码也可用,您可以查看其中的 repo 链接
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2015-09-02
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    相关资源
    最近更新 更多