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

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here.

However, the directive binds the element data to [value] of the input, and I require it to be 2-way bound to [(ngModel)]. The binding functions correctly, but the currency format display is not visible when first loaded; it only appears after clicking on the input and then clicking out. When bound to [value], however, it displays in currency format upon loading.

Here is the StackBlitz that I created from the Demo. I attempted to write a function to possibly tap into an onload event for the input, but I am unsure how to proceed. Is there a way to have it load with the ngModel formatted? The event does not appear to trigger on 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>

Answer №1

It seems like the custom directive you used is not available on Github, so I am unable to inspect its source code to understand what might be causing issues. Based on your code snippet, I suggest utilizing Angular's CurrencyPipe for formatting purposes.

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

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

Answer №2

Shortly after posting my query, I stumbled upon the solution. It was as simple as deconstructing the ngModel into property binding and event binding. So instead of using

 [(ngModel)]="mpPatient.ssissdiawardAmount"
, I now use

[value]="mpPatient.ssissdiawardAmount"
(input)="mpPatient.ssissdiawardAmount = $event.target.value"

Alternatively, Kevin Zhang's suggestion also does the trick.

Hoping this can assist someone else in the future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing the Material UI v5 theme with Typescript is impossible

I'm attempting to customize the color scheme of my theme, but I am encountering issues with accessing the colors from the palette using theme.palette. Here is a snippet of my theme section: import { createTheme } from "@mui/material/styles&qu ...

What is the proper way to retrieve an object from a json file?

My JSON structure looks like this: { "total": 4367, "page": 1, "per_page": 10, "paging": { "next": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=2", "previous": null, "first": "/v ...

Tips for turning off automatic retries in Nuxt 3 when utilizing useFetch

Struggling with the useFetch composable in Nuxt 3, I am facing an issue. I need the request to be triggered only once regardless of the result. Unfortunately, I haven't been able to figure out a way to achieve this. It keeps retrying when the request ...

Handle Ajax requests to prevent multiple submissions upon clicking

Seeking a solution to avoid multiple requests when the user clicks on the login or register button. The code provided below is not functioning as expected; it works fine the first time but then returns false. $('#do-login').click(function(e) { ...

The MaxDuration feature for a 5-minute time limit is malfunctioning on the Serverless Pro Plan, resulting in a 504 ERROR on

I am currently using Next.js@latest with App Directory My application is hosted on Vercel I'm experiencing a 504 error from Vercel and I'm on the pro plan. My serverless functions are set to run for up to 5 minutes, but usually, they only take ...

A message appeared in the console warning about Vue using canvas-datagrid

Everything is displaying correctly as I intended. However, there is a warning in the console: > vue.js:2 [Vue warn]: Unknown custom element: <canvas-datagrid> - did > you register the component correctly? For recursive components, make > sur ...

Issues with Angular's router outlet link functionality not performing as expected

I am encountering difficulties trying to create a link to a named router outlet in Angular. Let's focus on the most crucial part of the code: app-routing-module.ts: import { NgModule } from '@angular/core'; import { RouterModule, Routes } ...

Encountering an issue when trying to upload a file for the second time

I am currently working on a project where I need to upload an excel file and send it to an API using ReactJS. So far, I have been able to successfully send the file to the API. However, in my submit function, I want to reset the saved excel file from the s ...

What is the best way to efficiently handle onChange events for multiple input checkboxes in Reactjs?

When I attempt to assign an onChange event listener to a group of checkboxes, clicking on one checkbox results in all checkboxes being clicked and the conditional inline styles that I defined are applied to all of them. Here is the JSX code snippet: class ...

ModSecurity Action Causing AJAX Problem

An error is being triggered by the URL below with a message of "Modsecurity forbidden status code: 403". This URL is being returned from an AJAX call. like ? and active = ?&params='%ABCDE%'|1&element_id=hello If I remove %% from ABCDE ...

Incorporating a pre-existing component into a Vue.JS template through an onclick event: How can this

I'm trying to enhance my template by implementing a feature that allows me to add a component simply by clicking on a button. Let me give you a glimpse of what I have in mind: The component named Draggable.vue is the one I intend to incorporate upon c ...

Triggering a jQuery event upon clicking a link

Trying to achieve a specific functionality here. Clicking on an image triggers a lightbox, but right-clicking and opening in a new tab should lead to a different page. Instagram has a similar feature that I'm aiming for. Using <a href=""> doesn& ...

Issue with Chart.js V3.20: Struggling to Filter Legend Labels

Building a dynamic line chart using Chart.js with the capability of up to 19 datasets. The issue arises when there are less than 19 datasets, as the legend still displays for these unused datasets. Previously, a function was used in Chart.js 2.6.0 options ...

What could be causing the increased build size of my Polymer2 compared to Angular5?

After reading multiple blogs, I decided to go with the polymer2 framework instead of angular. Some sources claimed that Polymer contributes less to the build size for production compared to angular2/5. To test this theory, I created two demo projects - on ...

When using classList.replace, it should swap out every instance of the class xxx1yyy with xx

I attempted to swap a class and came across this helpful example here: javascript: replace classList that is inside a conditional Unfortunately, my attempt at modification (shown below) did not work. The use of classList.replace should change all instanc ...

Is it possible to create and manage a hierarchical menu in React (Next.js) using a generic approach?

Over the past few days, I've been working on a project involving a navigation bar built with TypeScript and React (Next.js). Up until now, I've only had a single level navigation, but now I'm looking to upgrade to a multi-level navigation me ...

Error: myFunction has not been declared

Can anyone figure out what's going on here? http://jsfiddle.net/sVT54/ <button onclick="myFunction()">Click me</button> <p id="demo"></p> function myFunction() { document.getElementById("demo").innerHTML="Hello World"; } ...

React TypeScript error: Cannot access property "x" on object of type 'A | B'

Just starting out with react typescript and I've encountered the following typescript error when creating components: interface APIResponseA { a:string[]; b:number; c: string | null; // <- } interface APIResponseB { a:string[] | null; b:number; d: ...

The chosen selection automatically deactivates the checkbox with a matching value

I am looking for a solution where selecting an option will automatically disable the checkbox with the corresponding value. The existing methods I have come across are static and rely on hardcoded values. <select name="pickOne" id="pickOn ...

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...