The Reactive Form I created is not displaying anything on the HTML page, but I can see the value being shown in the

I am facing an issue with my form. Initially, I created a simple form to create a product with the following details:

Description: "fff"
Line_num: "4"
Quantity: 545
Subtotal: 3027475
Unit_price: 5555
product_id: "11E826CB009A1864B430FA163EBBBC1D"
product_type_id: "11E7FC041F467AD4B09D00FF76874A55"

Next, I created a form group called addsale where I included the product value along with some additional values. In the component ts file, I fetched the product using this code,

this.products = this.ps.getProduct();
and successfully displayed the value in the console log.

Here is how I structured my form in the ts file:

this.addsale = new FormGroup({
    'invoice_number': new FormControl('', [Validators.required, Validators.nullValidator]),
    'invoice_date': new FormControl('', Validators.required),
    'client_id': new FormControl('', Validators.required),
    'amount_paid': new FormControl('', Validators.required),
    'notes': new FormControl('', Validators.required),
    'Subtotal': new FormControl('', Validators.required),
    'products': new FormArray([]),
    'total': new FormControl('', Validators.required),
    'contactNo': new FormControl('', Validators.required),
    'address': new FormControl('', Validators.required)
});

In the HTML file, I used the following code snippet:

<form [formGroup]="addsale" (ngSubmit)="onaddsale()">
    <tbody formArrayName="products">
        <tr class="form-group" style="cursor: pointer" *ngFor="let item of addsale.get('products').controls; index as i">
            <td>
                <input formControlName="Unit_price" type="number">
            </td>
            <td>
                <input formControlName="Quantity" type="number">
            </td>
            <td>
                <input formControlName="Description" type="text" name="Description">
            </td>
            <td>
                <input formControlName="Subtotal" readonly type="number"> 
            </td>
            <td>
                <button type="button" class="fa" (click)="onRemoveItem(i)">x</button>
            </td>
        </tr>
    </tbody>
</form>

Although the console correctly displays all values, nothing is shown on the HTML page. I would appreciate any assistance or suggestions on how to resolve this issue.

Thank you

Answer №1

From what I gather from your sample, it seems that you have not explicitly defined your FormArray. While you have declared it within your FormGroup, the FormControls within the FormArray are not defined.

In my case, the structure is as follows:

    this.customerForm = this.fb.group({
        firstName: ['', [Validators.required, Validators.minLength(3)]],
        lastName: ['', [Validators.required, Validators.maxLength(50)]],
        emailGroup: this.fb.group({
            email: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+')]],
            confirmEmail: ['', Validators.required],
        }, {validator: emailMatcher}),
        phone: '',
        notification: 'email',
        rating: ['', ratingRange(1, 5)],
        sendCatalog: true,
        addresses: this.fb.array([this.buildAddress()])
    });

It is important to note that a method is utilized to define the structure of the FormArray.

The method used for building an address looks like this:

buildAddress(): FormGroup {
    return this.fb.group({
            addressType: 'home',
            street1: '',
            street2: '',
            city: '',
            state: '',
            zip: ''
    });
}

Subsequently, it is these specific FormControl names that need to be bound to the formControlName property, rather than the names of the product properties themselves.

For additional comprehensive examples of forms, you can refer to: https://github.com/DeborahK/Angular2-ReactiveForms

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

How to use PHP for setting up a MySQL database?

Currently, I am immersing myself in the world of PHP and MySQL. I decided to take a shot at creating a basic HTML form along with a PHP script to set up a MySQL database. Unfortunately, when I tried to test it out, things didn't go as planned. Upon su ...

What is the best way to refresh the properties in an object?

I am working with a custom type object defined as follows: export interface IPupilFilter { Fullname: string; Gender: string; ClassType: number; Language: number; Class: number; ClassNumber: number; Phone: string; Movement: string; } public ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

Having trouble customizing the HTML range input?

I am looking to customize the appearance of a range input slider. Specifically, I want the slider to be green for the lower portion (where the thumb has moved) and grey for the remaining section. I have successfully changed the default styles from blue and ...

The Vue.js 3 error message "Property '$store' is not defined on the type 'CreateComponentPublicInstance'" highlights a common issue faced by developers

I'm currently working on a project using vue.js 3, typescript, and vuex 4. However, I encountered an issue while trying to use this.$store in my .vue file. Property '$store' does not exist on type 'CreateComponentPublicInstance<{}, { ...

The @testing-library/react-hooks library executes setTimeout function twice

Presenting my own unique React hook implementation: import { useEffect, useRef } from 'react' function useCustomInterval({ callback, interval, delay }) { const savedTimerId = useRef<NodeJS.Timeout>() useEffect(() => { const loo ...

How can you craft a single type that encompasses both the function signature and an array with the same structure?

In this scenario, I am facing a specific dilemma. type fnArgs = [string, number]; function test(a: string, b: number): void {} const x: fnArgs = ['a', 2]; test(...x); What I find interesting is that the values being passed to the test functio ...

Is it possible to create a ASP.NET 5 (Core) Website using TypeScript and Node (or ESM) modules within Visual Studio 2019, excluding Visual Studio Code?

After following a helpful guide on setting up TypeScript in an ASP.NET 5 website project using Razor Pages, I decided to enhance my typings with Node modules instead of just importing as 'any'. My goal was to integrate a Node module like EthersJ ...

Opt for a library exclusively designed for TypeScript

I am attempting to develop and utilize a TypeScript-only library without a "dist" folder containing compiled ".js" files. Here is the structure of my simple library: src/test/index.ts: export const test = 42; src/index.ts: import {test} from "./test"; ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Choose All / Deselect All Toggle for Checkbox Arrays Using the Name[] Naming Standard

I have a dynamic form with multiple sets of checkboxes that are initially checked by default. Upon form submission, arrays are created in the $_POST based on the checked checkboxes. The entire form is generated dynamically using PHP and data from a databas ...

The functionality of .submit() is not behaving as expected, although unbinding() can resolve the issue, it may

Short and sweet question: Form is set up to create a new user if the username is available (redirects to a confirmation page) Error message is displayed and form is stopped if the name is not available PHP code works fine, but there is a issue where it t ...

Global variable is null in Protractor test when utilized in separate class

I have a TypeScript class where I declared a global variable and used it in a method of the same class. Here is an example: First TypeScript Class: export class FirstTestDetails { baseProductDetails = { baseQty: null, basePrice: null, ...

Ways to troubleshoot opencv.js generating random values when applying cv.threshold

Whenever I choose an image and use cv.threshold, it outputs a strange number 6620912 The number seems to change at times https://i.sstatic.net/Tp9LP.png 6620912 Promise.catch (async) (anonymous) @ App.tsx:49 commitHookEffectListMount @ react-dom_client ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

What is the solution to the error message Duplicate identifier 'by'?

While conducting a test with the DomSanitizer class, I made some changes and then reverted them using git checkout -- .. However, upon doing so, I encountered a console error: Even after switching to a different git branch, the error persisted. Here are ...

Ways to verify the functionality of this specific custom hook (useRef)

Can anyone help me figure out how to pass the useRef as a parameter for testing this custom hook that uses ElementRef from React? import { MutableRefObject, useEffect, useState } from "react" export default function useNearScreen(elementRef: ...

Angular 6 offers a dynamic auto complete feature that enhances user

My Angular app has auto-complete functionality enabled. I am using ngFor to iterate over an array of objects and passing the index of the object array to a function for some operations. Below is the code snippet I have tried: template.html <mat-form ...