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.