Do Angular FormControl objects have the capability to accept input values of various types, or are they limited to TypeScript primitive types?

When creating a reactive form in Angular using FormControl objects in a FormGroup, I encountered an issue. While passing primitive arguments as values for an HTML input select control works fine, when passing an object of a self-defined class, the value in the FormControl gets reduced to [object Object].

The system setup I am working with includes: Angular CLI: 7.1.4; Node: 10.15.0; Angular: 7.1.4; rxjs 6.3.3; typescript 3.1.6; webpack 4.23.1; Linux rdz1 4.15.0-43-generic #46-Ubuntu SMP Thu Dec 6 14:45:28 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
    selector: 'app-header-notes',
    templateUrl: './header-notes.component.html',
    styleUrls: ['./header-notes.component.css']
})

export class HeaderNotesComponent implements OnInit {
    ndcForm = new FormGroup({
        noteType: new FormControl(''),
        noteDate: new FormControl(''),
        noteFor: new FormControl(''),
        noteTo: new FormControl(''),
        noteDetail: new FormControl(''),
        noteDetailVal: new FormControl(''),
        noteChkRefInvoice: new FormControl('')
    });

    ngOnInit() { this.onChanges(); }

    onChanges(): void{
        this.ndcForm.valueChanges
        .subscribe( val => console.log(val))
    }
}

Upon observing the console output like: {noteType: "credit", noteDate: "2019-01-01", noteTo: [object Object], ... }

I provided an object {param1: val1, parm2: val2} to "noteTo," expecting to see this value in the console. However, it shows [object Object] instead. It seems like the object has been stringified.

Answer №1

After some trial and error, I finally stumbled upon the solution. Instead of utilizing the following code snippet in the form:

<option *ngFor="let cargoAg of dfCargoAgs" [value]="cargoAg">{{cargoAg.nombre}}</option>

I had to switch it up to this:

<option *ngFor="let cargoAg of dfCargoAgs" [ngValue]="cargoAg">{{cargoAg.nombre}}</option>

It turns out that [value] is restricted to accepting only primitive types, whereas [ngValue] has the flexibility to handle objects of any class. Hopefully, this insight will prove useful to others facing a similar issue.

Answer №2

It appears that the object is undergoing a process known as "stringification".

To achieve the desired output in HTML format, you can customize the toString() method on your specific type.

If you wish to convert the formatted data back into an object of the custom type, you will need to create a conversion method, which may be tedious.

Alternatively, consider organizing the properties of your custom type within a nested structure like FormGroup inside your ndcForm FormGroup:

ndcForm: FormGroup = new FormGroup({
    noteType: new FormControl(''),
    noteDate: new FormControl(''),
    noteFor: new FormControl(''),
    noteTo: new FormGroup({
        any: new FormControl(''),
        custom: new FormControl(''),
        property: new FormControl('')
    }),
    noteDetail: new FormControl(''),
    noteDetailVal: new FormControl(''),
    noteChkRefInvoice: new FormControl('')
});

Ensure to extract and place each value from the object into the form accurately for bidirectional functionality.

Refer to Angular documentation on creating nested FormGroup structures for further guidance.

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

Would it be frowned upon to rely on store instead of data binding for inter-component communication when accessing my data?

Within my current framework, I house the primary business logic within selectors and effects. Components are able to request data by triggering an action that queries the necessary information through selectors. Apart from instances where *ngFor is utili ...

The information is not displayed on the Angular multi-select dropdown

Having an issue where the data is stored in an object and when I try to map it to an ng multiselect dropdown, the values are not displaying in the dropdown. This is happening with Angular 7. <div class="form group mltslt" *ngIf="individual==true"> ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

Guide on Generating Dynamic JSON to Set and Retrieve Values for Forms and Displaying the Bound Values

I'm a beginner in Ionic 3 and I'm having trouble creating a page that redirects to another page without validation. I want to display the data on the new page, but it's not working. Please help! I also want to create a dynamic JSON object a ...

Efficient method to access two arrays simultaneously and combine them into an associative array in JavaScript

When using Ajax to return a table, you have the option of separating column names and row values. Here are two ways to do it: let columns = ["col1", "col2", "col3"]; let rows = [ ["row 1 col 1", "row 1 col 2", "row 1 col 3"] , ["row 2 col 1", "r ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

The Angular template loads and renders even before the dynamic data is fetched

I'm encountering a frustrating issue where the page loads before the data is retrieved. When I log the names in $(document).ready(), everything appears correct without any errors in the console. However, the displayed html remains empty and only shows ...

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Consider pushing items onto an array only once when the condition is met, instead of adding to the array every

I have been tasked with importing Excel files containing customer orders into my web application. The process involves converting the data in the file into an object of arrays, where each array represents a row from the Excel sheet. Once the data is impor ...

Tips for personalizing Ion text area in Ionic?

Seeking assistance on how to effectively utilize ion-textarea. As a novice in the realm of Ionic, I am encountering various challenges while working with this feature. The issue lies in the fact that instead of displaying a scrollbar on the right side, the ...

Obtain the value of a template variable in Angular 2

I am seeking information on how to access the values of selected items in templates. Specifically, I want to understand how to retrieve the selected value of IPMIDisplayTime and IPMIDisplayTime within the template for later use. import {ViewChild, Elem ...

Tips for effectively mocking a service class in a hybrid Angular project to facilitate unit testing

I'm currently working on a hybrid Angular project, but I've encountered some challenges with unit testing. Despite trying out this solution, it doesn't seem to be effective for my particular project. I keep receiving an error when running ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

What is the most effective method for delivering a Promise after an asynchronous request?

Currently, I am working on creating an asynchronous function in TypeScript that utilizes axios to make an HTTP request and then returns a Promise for the requested data. export async function loadSingleArweaveAbstraction(absId : string) : Promise<Abstra ...

Encountering the error "tsx is not defined" during a Jest test in a React/TypeScript project

I'm currently working on implementing Jest tests within a React project that has enforced TypeScript settings. In a simple test.tsx file located in the test folder, I have the following code: import React from 'react'; describe('Test& ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

Utilizing ngx-bootstrap to enhance Bootstrap dropdown functionality

I initially tried to set up ngx-bootstrap in Angular 2 by using the following command: npm install ngx-bootstrap bootstrap --save Then, I included these lines in angular-cli.json: "../node_modules/bootstrap/dist/css/bootstrap.min.css". In app.compone ...

The Eslint tool encountered an issue: Parsing error - it seems that the function ts.createWatchCompilerHost is

What could be causing this error message to appear? Here is my current configuration: "parser": "@typescript-eslint/parser", "parserOptions": { "project": "tsconfig.json", "tsconfigRootDir& ...