I have a form with a FormArray that dynamically adds rows with multiple fields, including unit, quantity, and remarks. Here’s a snippet of my template where I loop through the unitDetails FormArray:
<tbody formArrayName="unitDetails">
<tr *ngFor="let row of unitDetails.controls; let i = index" [formGroupName]="i">
<td>{{ i + 1 }}</td>
<td><input class="form-control" formControlName="unit" placeholder="Enter Name" /></td>
<td><input class="form-control" formControlName="quantity" placeholder="Enter Quantity" /></td>
<td><input class="form-control" formControlName="remarks" placeholder="Enter Remarks" /></td>
<td><a class="btn btn-danger" (click)="removeUnitRow(i)">Remove</a></td>
</tr>
</tbody>
The form is structured like this:
this.form = this.fb.group({
unitDetails: this.fb.array([]), // Group for Unit, Quantity, Remarks
discountDetails: this.fb.array([]), // Group for Qty From, Qty To, Discount, Cash Discount
statusGroup: this.fb.group({
status: ['']
})
});
I want to add a valueChanges handler for the quantity form control inside the unitDetails FormArray to ensure that only numeric values are allowed. Here’s what I’ve tried so far:
form.get('quantity')?.valueChanges.subscribe(values => {
console.log(values);
});
However, this doesn’t work because quantity is inside a FormArray, and I’m unable to access it directly.
How can I track changes for the quantity field within the FormArray and modify the value to accept only numbers? I would also like to prevent non-numeric input.
Can anyone provide a solution or guide me on how to achieve this in Angular?
ARUN PRAGASH is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
If you want only numeric values, then you should set it as type="number"
.
<td><input class="form-control" type="number" formControlName="unit" placeholder="Enter Name" /></td>
To save you some complicated code, I suggested this simple method of using the (input)
event which will fire the same as valueChange
and you can use this with less amount of code.
<tbody formArrayName="unitDetails">
<tr *ngFor="let row of unitDetails.controls; let i = index" [formGroupName]="i">
<td>{{ i + 1 }}</td>
<td><input class="form-control" formControlName="unit" placeholder="Enter Name" (input)="unitChange($event)"/></td>
<td><input class="form-control" formControlName="quantity" placeholder="Enter Quantity" (input)="quantityChange($event)"/></td>
<td><input class="form-control" formControlName="remarks" placeholder="Enter Remarks" (input)="remarksChange($event)"/></td>
<td><a class="btn btn-danger" (click)="removeUnitRow(i)">Remove</a></td>
</tr>
</tbody>
Then you can acess the value like:
unitChange(event: any) {
const value = event.target.value;
console.log('unit change: ', value);
}
If you decide use with valueChanges, you’ll need to manage subscriptions for each control in the FormArray dynamically, like:
this.form.get('unitDetails')?.valueChanges.subscribe((unitDetails: formArry[]) => {
unitDetails.forEach((unitDetail, index) => {
const quantityControl = (this.form.get('unitDetails') as FormArray).at(index).get('quantity');
quantityControl?.valueChanges.subscribe(value => {
console.log(value) // Now you can access the value
});
});
});
But for your case, my recommendation for you is create a directive, or apply a validador directly in the formControl.
Validador, can be something like that:
this.fb.group({
unit: [''],
quantity: ['', Validators.pattern('here you must to create a numeric pattern')], // Numeric validation
remarks: ['']
});
You can read more here Validator Pattern doc
Or a directive:
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appNumericOnly]'
})
export class NumericOnlyDirective {
constructor(private ngControl: NgControl) {}
@HostListener('input', ['$event'])
onInput(event: Event): void {
const inputElement = event.target as HTMLInputElement;
const numericValue = inputElement.value.replace(/[^0-9]/g, ''); // Remove non-numeric characters
if (inputElement.value !== numericValue) {
inputElement.value = numericValue;
this.ngControl.control?.setValue(numericValue); // Update the FormControl value
}
}
}
After create your directive you need to import it, in your component and add to the quantity field in your FormArray template;
<td><input class="form-control" appNumericOnly formControlName="quantity" placeholder="Enter Quantity" /></td>
You also can read more in the Official Angular documentation