Shank
Shank

Reputation: 1398

What event can be used to detect that the value has changed for input, Angular

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>
    

 

Upvotes: 0

Views: 694

Answers (1)

Darshan Malani
Darshan Malani

Reputation: 476

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);

}

Upvotes: 0

Related Questions