Search code examples
javascriptangulartypescriptangular-materialangular-ngmodel

binding ngModel instead of value to a custom Angular directive for currency input


I'm currently using a custom mat-input-currency format directive to automatically format my field inputs to currency. the npm repo is found here.

However, the directive binds the element data to [value] of the input i and I need to 2-way bind it to [(ngModel)] the binding works but the currency format display doesn't show when it is first loaded, only when clicking on the input and then going blur. binding it to [value] however, displays it in currency format on load.

here is the StackBlitz I forked from the Demo I tried writing a function maybe to tap into an onload event for the input but not sure how to go about that. is there a way to make it load with the ngModel formatted? the event doesn't seemed to kick off in the onload.

  <mat-form-field *ngIf="mpPatient.ssissdiawardLetter=='Y'" appearance="standard">
          <mat-label>SSI/SSDI Award Amount</mat-label>
          <input matInput type="text"
         (onload)="onLoadCurrencyEvent($event, mpPatient.ssissdiawardAmount)"
          mvndrMatCurrencyFormat [allowNegative]="false" [currencyCode]="'USD'"
          [(ngModel)]="mpPatient.ssissdiawardAmount"
          (blur)="updateUSAmount($event, mpPatient.ssissdiawardAmount)">
        </mat-form-field>

Solution

  • Since the directive you used which I can not found the source code in github, so I don't know what happened in this custom directive. And from your code, I think you can just you Angular CurrencyPipe, it will provide the formar you want.

    <mat-form-field class="example-full-width">
                <input matInput type="text"
          [value]="testvalue | currency:'USD'" />
    </mat-form-field>
    

    I forked you demo and just for your reference: https://stackblitz.com/edit/angular-3gatlt?file=src/app/app.component.html