Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsulate it within a custom component.

For this input, I am utilizing primeng's inputNumbers functionality.

The essence of my custom-input-number component can be summarized as follows:

HTML file :

<span class="p-float-label w-100" [formGroup]="form">
  <p-inputNumber
    formControlName="number"
    [disabled]="disabled"
    (onInput)="onChange($event)"
    (onBlur)="onTouched()">
  </p-inputNumber>
  <label for="{{ id }}" class="custom-input-label">{{ label }}</label>
</span>

<small class="unselectable">
  {{textValidators}}
</small>

Typescript file :

import { ChangeDetectorRef, Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors } from '@angular/forms';

@Component({
  selector: 'ngx-custom-input-number',
  templateUrl: './custom-input-number.component.html',
  styleUrls: ['./custom-input-number.component.scss'],
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => CustomInputNumberComponent),
      multi: true,
    },
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputNumberComponent),
      multi: true,
    },
  ],
})
export class CustomInputNumberComponent implements OnInit, ControlValueAccessor {

  // Rest of the code here...

}

Using this custom-input-number component in another component is straightforward. You simply need to include it and specify the formControlName like so:

  <form [formGroup]="form"
    <ngx-custom-input-number [label]="..." formControlName="number"> </ngx-custom-input-number>
  </form>

An issue arises when the value entered into the input field is sent to the server. The formatting and structure of the data change at that point. For instance:

number : {
    formattedValue : '423',
    originalEvent : { isTrusted : true},
    value : 4234
  }

To address this problem without causing widespread changes to the entire project, I aim to adjust the custom-component to only send the value, disregarding other supplementary data. It is worth noting that this discrepancy was not present in Angular 12, but cropped up after upgrading to Angular 16.

Please Note: this dilemma surfaced specifically after migrating the project from Angular 12 to Angular 16.

Answer №1

Make the following changes to the HTML code.

<span class="p-float-label w-100" [formGroup]="form">
  <p-inputNumber
    formControlName="number"
    [disabled]="disabled"
    (onInput)="onChange($event.value)"
    (onBlur)="onTouched()">`enter code here`
  </p-inputNumber>
  <label for="{{ id }}" class="custom-input-label">{{ label }}</label>
</span>

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

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

Discovering the right category for a general component: A step-by-step guide

How about creating a new list component that can work with an array of objects? <script setup lang="ts"> const props = defineProps<{ items: Record<string, unknown>[], selected: Record<string, unknown> | null field: stri ...

Receiving a notification when attempting to log in with incorrect credentials

I am currently working on an Angular login page implementation using a username and password setup. When the user enters incorrect credentials, I want to display an alert message indicating the same. Here is the HTML code snippet for the form: <form [f ...

Having trouble parsing the ICU expression. Utilizing angular for internationalization

I need to convert an array of left-menu items into another language, and I am encountering an error in my code. Here is the snippet: left-menu.component.html <ng-container *ngFor="let m of menuItems; let last = last"> <a mat-list-it ...

The browser fails to implement styling prior to a demanding workload

Is it possible to refresh a section of my webpage that contains numerous DOM elements? My ideal approach would be to hide the section using visibility: hidden;, then redraw it, and finally set visibility back to visible;. However, I've encountered an ...

What is the process for programmatically importing a module into the local scope in Node.js?

The coding environment is using a browser and the bundle tool being used is webpack. In my router.js file, I have the following code: import foo from './views/foo.vue' import bar from './views/bar.vue' import zoo from './views/zoo. ...

Controlling HTML5 Video Playback with JavaScript: Pausing at Custom Frames

I need to implement a feature in my web application where I can pause an HTML5 video at specific frames using pure JavaScript, not based on minutes. <video id="media-video" controls> <source id="media-source" src="media/video.mp4" typ ...

Searching for data in Node.js using Mongoose and dates

I'm in search of a way to execute a specific query with mongoose. In my mongodb database, I have data structured like this: "startDateTime" : ISODate("2017-03-22T00:00:00.000Z"), "endDateTime" : ISODate("2017-03-27T00:00:00.000Z"), My goal is to r ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...

Creating UV coordinates in THREE.js

I've been working on bringing a model into a scene using the OBJ loader in THREE.js. Initially, I had no issues importing the geometry and visualizing it with MeshNormalMaterial. However, as soon as I tried to use textures that require UV coordinates ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Finding the index of a nested div element with a click event using jQuery

I'm currently working on a click event to retrieve the index of the outermost parent div, but I'm facing some difficulties in getting it to work. Here is a snippet showcasing a list of several divs: <div class="owl-item"> <div class= ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

How to override an event in JavaScript when a specific value is entered

I am looking to implement a system with complex conditions. The goal is to have an alert appear when a value is inputted and the button is clicked. First, a confirmation message Have you input ? should be displayed, followed by clicked with input. If no va ...

Using Express and Node.js, fetch an image from one localhost and transfer it to another localhost

I am currently developing a NodeJs and Angular app The server is running on http://localhost:9000 While the app itself runs on http://localhost:4200 One of my endpoints looks like this http://localhost:9000/users, which I use to fetch all user data The ...

modifying Redux state according to the position in an array

In my food truck app, I have stored customer orders in the redux state as an array of objects. Each order includes a list of items selected by the customer, along with the count, name, and total price for each item. For example: state.order = [ {item: " ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Increase the placeholder's line height and font size for the InputBase component in Material UI

Hello, I am new to material UI and currently using it for my website development. I am trying to customize the placeholder of the inputbase in material ui by increasing their lineHeight and fontSize. However, I am having trouble accessing the placeholder A ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Automatically Formatting Currency in Angular 6 with Keyup

I am currently facing an issue with using the keyup event in an input element that has a currency pipe in my Angular 8 application. <input placeholder="€0.00" (keyup)="onKey(pointIndex, $event.target.value, item.quantity)" value="{{item.unitPriceWith ...