How to convert form fields into JSON format using Angular 2

Currently, I am in the process of learning angular2 and have encountered a roadblock. I have created a form where the values are populated through JSON. The form consists of both pre-filled fields and text input fields where users can enter data and select options. My goal is to capture these form values as JSON based on user input. I believe Observables might be the solution, but I am unsure about how to implement them. Can anyone provide guidance on how I can achieve this?

Here is the code snippet that I have developed:

<ul>
  <li>
    <div *ngFor="let question of questions">
       <div class="row">
          <div class="col-md-12">
             <md-input placeholder="{{question.displayKey }}"></md-input>
          </div>
       </div>
       <div class="row row-bordered">
          <div class="col-md-8"> {{question.displayKey }}</div>
          <div class="col-md-4">  
             <md-radio-group>
               <span>
                 <md-radio-button *ngFor="let option of question.choices" name="{{option.displayKey}}" [value]="option.displayKey" aria-label="Yes" tabindex="0">{{option.displayKey}}</md-radio-button>
               </span>
             </md-radio-group>
           </div>                            
      </div>                        
    </div>
  </li>
</ul>

JSON Output:

"questions": [
  {
    "code": "12345",
    "displayKey": "Question1?",
    "required": true,
    "questionType": "Boolean",
    "choices": [
       {
         "choiceCode": "true",
         "displayKey": "Yes"
       },
       {
         "choiceCode": "false",
         "displayKey": "No"
       }
     ]                           
  },
  {
    "code": "aw345y",
    "displayKey": "Question2?",
    "required": true,
    "questionType": "Boolean",
    "choices": [
       {
         "choiceCode": "true",
         "displayKey": "Yes"
       },
       {
         "choiceCode": "false",
         "displayKey": "No"
       }
     ]                          
   }
 ]

Answer №1

<form #myForm="ngForm" (ngSubmit)="submitMyForm(myForm.value)">

in the typescript file

submitMyForm(formData){
    console.log(formData);
}

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 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

Understanding the tsconfig.json file in an Angular project

I encountered the following error in my tsconfig.ts file: 'No inputs were found in config file 'c:/Projects/Angular2//src/tsconfig.json'. Specified 'include' paths were '["src/**/*.ts"]' and 'exclude' paths ...

Tips for configuring identical libraries under different names

As a Japanese web developer, I struggle with my English skills, so please bear with me. Currently, I am utilizing an npm library. I have forked the library and made some modifications to it. In order to incorporate these changes, I updated my package.js ...

What sets apart the ? operator from incorporating undefined in the type declaration?

Can you explain the distinctions among these options? type A = {a?: string} type A = {a: string | undefined} type A = {a?: string | undefined} In what scenarios would one be preferred over the others? For more information, visit: https://github.com/mic ...

Transform a collection of interfaces consisting of key-value pairs into a unified mapped type

I have a set of interfaces that describe key-value pairs: interface Foo { key: "fooKeyType", value: "fooValueType", } interface Bar { key: "barKeyType", value: "barValueType", } interface Baz { key: "bazKeyType", value: "bazValue ...

What are the steps to retrieve a Json Object from an Array while extracting information from Rapid API?

Utilizing axios to fetch data from a GET API on RapidAP returns an array of JSON objects, as illustrated in the images below. How can I implement Typescript within React to specifically extract the data of these JSON objects from the array according to my ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Guide on integrating external libraries with Angular CLI

I've been working on incorporating external libraries into my project, and I've been following the instructions provided here. While I know it's possible to use CDNs in my index.html, I'm interested in learning how to do it using TypeS ...

I'm feeling lost when it comes to rendering these components using styled-components in reactjs

Include the BarItem and BarItemSelect components inside the link when the condition is true, both styled with a specific CSS class. Currently, these are two separate components... I'm unsure how to achieve this const S = { BarItem: styled.a` pos ...

Issue with Sending Messages using SignalR in .NET and Angular

I am attempting to make a simple SignalR example work, following Microsoft's tutorial and using the Weatherforecast .NET/Angular SPA from Visual Studio as a starting point for a project I plan to integrate SignalR with in the future. You can find the ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

Converting SASS in real-time using SystemJS

I have been reading various blogs discussing the use of SystemJS and SASS transpiling, but most of the examples I come across involve pre-processing SASS files before importing them into JavaScript code. However, I am interested in being able to directly i ...

retrieve data from URL parameters (navigation backward)

When navigating from the main page to the transaction page and then to the details page, I have implemented a go back feature on the details page. Using the state, I pass data when navigating back so that I can access it again from the transaction page. H ...

Is there a way to apply a css class to all nested elements in Angular 6 using Ngx Bootstrap?

I've defined a CSS class as follows: .panel-mobile-navs > ul > li { width:100% } Within the HTML, I am utilizing Ngx-bootstrap for a series of tabs like this: <tabset class="panel-mobile-navs" > ... </tabset> My intention is to ...

What are the steps for creating a custom repository with TypeORM (MongoDB) in NestJS?

One query that arises is regarding the @EntityRepository decorator becoming deprecated in typeorm@^0.3.6. What is now the recommended or TypeScript-friendly approach to creating a custom repository for an entity in NestJS? Previously, a custom repository w ...

Angular2 Filtering Problem

Trying to create a filter in angular2, I have constructed an array of products as shown below: private items = ["Apple", "Banana", "Orange"]; Below is the code for my filter pipe: import {Pipe} from 'angular2/core'; @Pipe({name:'filter&a ...

Is there a way to prevent future dates from being selected on angular p-calendar?

I need help with disabling future dates in a calendar datepicker input field. Here's how I'm currently using it: <p-calendar maxDate="dateTime" showTime="true" hourFormat="12" showButtonBar="true" [(ngModel)]="dateTime" name="timeOfUse" requ ...

How can a button click function be triggered in another component?

These are the three components in my dashboard.html <top-nav></top-nav> <sidebar-cmp></sidebar-cmp> <section class="main-container" [ngClass]="{sidebarPushRight: isActive}"> <router-outlet></router-outlet> & ...