a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to bind all the data in the database. If anyone has experience with this, please guide me.

documentList: [
          {
            'IsSpecifications': false,
            'IsSpecificationscomment': ''
          },
          {
            'IsDrawSchedule': false,
            'IsDrawSchedulecomment': ''
          },
          ...
        ];
<div class="my-3">
                        <ejs-checkbox label="isSpecifications()" labelPosition="Before"></ejs-checkbox>
                    </div>
                   ...
                    </div>

Within the database, I utilize the documentlist field where all checkbox values are stored as a JSON string.

Answer №2

Check out the Stackblitz for this code snippet

This answer serves to provide a demonstration on Stackblitz rather than a tutorial.

To fully comprehend the code, you need to have a grasp of the following:

Instead of using Control Value Accessor, you can also pass in a form group as an input based on your preference.

A Brief Overview

By implementing the control value accessor on a custom component like ejs-checkbox, you can easily bind it using the code snippet below:

<ejs-checkbox formControlName="{{ i }}"></ejs-checkbox>

Any changes made will be automatically reflected in the overall form group.

Try modifying the form and observe the console logs displaying valueChanges.

I've opted for a form array for the document list to accommodate potential size changes. However, if size is fixed, consider using form controls instead.

Included is an exampleSave() function that converts the form group value to match your documentList. You can JSON.stringify this data and send it to the server as stated in your question.

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

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

The argument type provided for returning an object in Rxjs switchmap is not valid

I have created a service in Angular that fetches data from different services and combines it with the initial service's data. If the initial service returns empty data, there is no need to call the second service. Here is the code: searchData(): Obs ...

What is the process for displaying node_modules directories in a json/javascript document?

Exploring ways to showcase the dependencies within my d3.js tree, I am curious if it's possible to dynamically list the dependencies' names in a JSON file or directly within the javascript file. I'm puzzled by how JavaScript can access folde ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Issue: Unable to link to 'FormGroup' because it is not recognized as a valid property of 'form'

app.module.ts import { BrowserModule } from '@angular/platform-browser'; import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AppRoutes} from './app.routin ...

Issue with Angular4: Unable to select [selected] attribute on initial load

Here is a code snippet to select a department: <select name="department" class="form-control select" [(ngModel)]="departments" formControlName="departmentControl"> <option *ngFor="let department of departments" [ngValue]="department" [se ...

When implemented Angular SSR, I encountered an unexpected error: ''An uncaught exception occurred: npm ERR! code ERESOLVE

I'm currently in the process of implementing Server-Side Rendering for my application by closely following the instructions provided here in the documentation The initial step involves running ng add @nguniversal/express-engine Unfortunately, this r ...

Updating a database from a JSON patch: A step-by-step guide

I receive a complex json data every few hours. Within this data, there is a Game object containing a list of Player objects, each with a list of Training objects in addition to other fields such as integers, strings, and lists of strings. If the Game objec ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement) Upon sending data to the server as shown below, the body appears empty. Server // Route for POST method app.post('/pass', function (req, res) { ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

AngularFirestoreCollection can be thought of as a reference to a collection within Firestore, which

Hey there, I need some help with the following code snippet. Data link service file private dbUser = '/users'; constructor(private firestore: AngularFirestore) { this.userCollection = firestore.collection(this.dbUser); } Now in my component fi ...

Tips on expanding typings in TypeScript?

In my software library, there exists a map function with the following definitions: function map<T, U>(f: (x: T) => U, a: Array<T>): Array<U> function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U> Furtherm ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

The argument representing 'typeof Store' cannot be assigned to the parameter representing 'Store<AppState>'

I'm encountering an issue while trying to expand a service in Angular that utilizes ngrx. The error message I'm receiving is as follows: Argument of type 'typeof Store' is not assignable to parameter of type 'Store<AppState>& ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

A Defer statement in TypeScript that mimics Go's functionality

Is there an equivalent to Go's Defer statement in TypeScript? I find it tedious to write cleanup code in various parts of a function. Searching for a simpler alternative. I tried searching on Google, but couldn't locate any relevant information ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

What is the best way to transfer JSON data from one file to another file in JSON format?

A unique json file is at my disposal, revealing an intriguing look: *{ "_id": "5f70aa5c04d7a034fc19e8969b000599", "contributors": null, "coordinates": null, "created_at": "Wed May 06 09:32:46 +0000 2020", ...