How to Create valuechange detection of the formcontrol which is inside the form array of the...

Discussão em 'Angular' iniciado por ARUN PRAGASH, Dezembro 4, 2024.

  1. ARUN PRAGASH

    ARUN PRAGASH Guest

    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?

    Continue reading...

Compartilhe esta Página