0
votes

Im creating a directive which is added on an text input, it needs to format the currency inputted.

I have two HostListeners; blur and focus. Upon blur event, I grab the value, format it and assign it to the ngControl. Upon focus, I unformat it and assign it back.

I am injecting ngControl, I can use the valuechanges on it and format it, but some other code sets the value with emitEvent false, so this doesn't get triggered. hence it doesnt format it.

Im looking to see if there is an event that can be used which gets triggered with emitEvent false.

        constructor(private currencyPipe: CurrencyPipe, private ngControl: NgControl) {}
    
        @HostListener('blur', ['$event']) format(event) {
        let value =  event.target.value;
        if (value ) {
          value = this.format(value );
          this.ngControl.control.setValue(value , { emitEvent: false });
        }
       
        private format(value: any) {
            if (value && value !== '-' && !isNaN(value)) {
              return this.currencyPipe.transform(value, this.currencyCode, '', this.digitsInfo, this.locale);
            }
            return value;
       }

HTML

<mat-form-field color="accent" [appearance]="formFieldAppearance" class="table-column-input mr-n1">
   <input
      autocomplete="off"
      appCurrencyFormatter
      matInput
      formControlName="exchangeRate"
   />
</mat-form-field>
    

 
1
Could we see how you expect to use this directive? i.e., will it be used in conjunction with a reactive form model? - garbear
added more code, so basically when the user on focus on the input, I remove all the commas, after the user leaves the input I format it with the @HostListener('blur', ['$event']) - Shank
I tried this out and it seems to work for me. The only difference in mine is that I used the exported function formatCurrency from @angular/common rather than injecting the currencyPipe. I don't see why the currencyPipe would cause any issues so I don't think that's the issue. It would be helpful to have a stackblitz for this issue. - garbear
this wont work if the value is changed by the app, for example formControl.setValue(100000, {emitEvent: false}); the HostListener wont get triggered - Shank
Do you expect formControl.setValue() to trigger a DOM event? - garbear

1 Answers

0
votes

HTML

<mat-form-field appearance="outline" class="common-form-field-width"> <mat-label>{{ 'PRICE' | translate:lang }}</mat-label> <input type="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" matInput formControlName="actual_price" [value]="actual_price" [placeholder]="'PRICE' | translate:lang" (ngModelChange)="onChangePrice($event)"> </mat-form-field> 


Component.ts file

onChangePrice(event: any) {

  console.log(event);

}