Format input value after Angular2 ngModel is applied

佐手、 提交于 2019-12-06 14:28:21
  ngAfterContentInit() {

    this.model.valueChanges.subscribe(value => {
      if(value) {
        const parsed = parseInt(value.replace('$', ""));
        this.model.valueAccessor.writeValue(new CurrencyPipe().transform(parsed, 'USD', true));
      }
    })
  }

In your template:

<div>
  <input type="text" currencyInput [ngModel]="initModel" name="number"/>
</div>

One possibility is to bind to a getter/setter method that will transform the field to the correct format, and then return it back to the original format after it is modified, as per below

typescript:

 AnnualRevenue: number;
  get AnnualRevenueFormatted():string{
    return  this.AnnualRevenue !== undefined ?  `$${this.AnnualRevenue.toLocaleString()}`: '$0';
  }

  // strip out all the currency information and apply to Annual Revenue
  set AnnualRevenueFormatted(val: string) {
    const revenueVal = val.replace(/[^\d]/g, '');
    this.AnnualRevenue = parseInt(revenueVal);
  } 

and in the component view

<input type="text" class="text-input" [(ngModel)]="accountInfo.AnnualRevenueFormatted"  />
Saima Gul

On my directive I have applied the solution mentioned in this post:

ngAfterContentInit() {
    this.model.valueChanges.subscribe(value => {
        if (value) {
            const parsed = parseInt(value.replace('$', ""));
            this.model.valueAccessor.writeValue(new CurrencyPipe().transform(parsed, 'USD', true));
        }
    })
}

and it works for me.

See my Post : Directive display ng-model input value as currency in angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!