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

When using momentJs to add days, it will return a moment object rather than a

How can I add 7 days to a date using momentJs in my Angular project? let startDate = "2018-08-16T02:00:00.242Z"; let newDate = moment(startDate).add(7, 'days'); I was expecting to receive the date after adding 7 days, but instead I get a momen ...

The function userRole consistently returns "user" regardless of the role being admin

I am facing an issue with the getTeamMembers() method while trying to identify which members are admins in a private team. Even though I am logged in as an admin, the userRole value always shows as "user". Can anyone assist me with this problem? import { ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

What is the best way to make one element's click event toggle the visibility of another element in Angular 4?

Recently diving into Angular, I'm working on a feature where users can toggle the visibility of a row of details by simply clicking on the item row. The scenario involves a table displaying log entries, each with a hidden row underneath containing spe ...

Can you explain the purpose of the "letter:" included in the code and how it is utilized?

g: function testFunction() { return true; } h: function anotherTestFunction() { } i: console.log('test') I'm intrigued by the mystery of this code snippet. As is written, I am executing it in NodeJS version 16 or higher and trying to un ...

The computed function is unable to find the property on the specified type

I am a beginner in TypeScript. I have encountered an issue with the code below, which runs perfectly fine in JavaScript but is not compiling here. export default { data: function() { return { data: [ 'Angular', 'A ...

I'm trying to figure out how to redirect only the empty path using the new router in Angular 2. Can anyone

Environment: Upgraded to RC4 with brand new router Here is the current configuration of my router.. export const routes: RouterConfig = [ {path: 'search-documents', component: SearchDocumentsComponent}, { path: '', pathMat ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

Tips on applying borders to dynamically generated content in jspdf autotable, similar to a template

Having trouble adding borders to my PDF generated using jsPDF autotable. I want the layout to match the template, can someone assist me in resolving this issue? I need the header border to consist of two lines, similar to the template image provided below ...

Tips for preventing duplication of the interface in Typescript React

Embarking on my first Typescript app, I am determined to maintain a structured approach by keeping styles and components in separate files. With an ambitious project scope of numerous components, I intend to utilize props for calling classes, ensuring each ...

Can type information be incorporated during compilation?

Consider the code snippet below: function addProperties(keys: String[]): Object { // For illustration purposes, this is a specific return return { firstProperty: "first_value", secondProperty: "second_value" }; } export defaul ...

What is the best way to modify a data parameter in Angular 2?

I am facing an issue while trying to change a data parameter in my component file: this.commandList.ListesCommandesATransmettre.forEach(data => { this.catalogs.forEach(catalog => { if (catalog.Libelle === data.Catalogue) { if ...

Guide on retrieving an ArrayList() from intricate function in Angular

Simplicity is the key to my question. Let's take a look at this Angular method: getAllOrdersHeaders(){ this.getAllOrdersIds().subscribe(idList=>{ idList.forEach(id=>{ this.ordersCollection.doc(id).collection('metadata&apo ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

Utilizing Angular's Dynamic Component Import and Loading capabilities

Looking to develop a portal that can dynamically load Angular components without the need for explicit imports. I've heard about using ComponentFactoryResolver for this purpose, but hoping to have the ability to store components in separate files or r ...

The angular httpTestingController.expectOne method throws an error, even when the httpClient's get method has

I have an issue with my testing in Angular. I am trying to test a simple function within a service: getReports(url: string): Observable<Report[]> { return this.http.get<Report[]>(url); } This is the test that I have written: it(`should c ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Leveraging Angular 4 with Firebase to extract data from a database snapshot

My dilemma lies in retrieving data from a Firebase DB, as I seem to be facing difficulties. Specifically, the use of the "this" operator within the snapshot function is causing issues (highlighted by this.authState.prenom = snapshot.val().prenom) If I att ...

Implementing Angular2 with an external filter in ag-Grid

I am looking to implement external filtering on ag-grid using angular2. After reviewing the ag-grid example on github, it appears that external filters are not implemented and a similar question remains unanswered. Is there a way to incorporate external f ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...