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

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...

Angular: Dynamically changing checkbox's status from parent

I'm in the process of developing a switcher component that can be reused. The key requirement is that the state of the switch should only change after an API call is made at the parent component level. If the API call is successful, then the state cha ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Using the `forwardRef` type in TypeScript with JSX dot notation

Currently, I am exploring the different types for Dot Notation components using forwardRef. I came across an example that showcases how dot notation is used without forwardRef: https://codesandbox.io/s/stpkm This example perfectly captures what I want to ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

Can someone confirm if I am importing this png file correctly? I am encountering an error with Vite, here is my code

Error: TypeScript+ React + Vite [plugin:vite:import-analysis] Failed to find import "./assets/heropic.png" in "src\components\Hero.tsx". Are you sure the file exists? Hello fellow developers! I am new to working with react and typescript. Curren ...

Exploring Angular 17 with the Nebular framework through the implementation of Standalone Components

Exploring Angular in combination with Nebular for UI has been my recent focus. To get started, I decided to create a quick app and dive into the intricacies of these frameworks. After setting up Angular, I initialized a new app using app new my-app. I en ...

Error occurred due to changed expression after validation

I am facing an issue in my Angular app while implementing checkboxes with ngModel. When I try to implement it, I encounter the following error message. Can someone please help me resolve this problem? Error core.js:5873 ERROR Error: ExpressionChangedAfter ...

Setting the value of a form control within a form array in an Angular reactive form can be achieved by following these steps

I have a reactive form with multiple entity entries: this.entityDetailsForm = new FormGroup({ entitiesArray: new FormArray([ new FormGroup({ id: new FormControl(), name: new FormControl(), startDate: new Form ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Restricting types does not appear to be effective when it comes to properties that are related

I am working with a specific type that looks like this: type Props = { type: 'foo'; value: string; } | { type: 'baz'; value: number; }; However, when using a switch statement with the type property in TypeScript, the program in ...

JavaScript heap exhausted while running Docker container

Typically, I start my application by running npm run dev. The package.json file contains a script like the one below: "scripts": { "dev": "nodemon server.ts", } Everything is working fine in this setup. I have cr ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

Angular2 - Incorporating a New Attribute

I am working with the following Angular2 code: <ngx-datatable-column prop="id" name="ID"> <template ngx-datatable-cell-template let-row="row" let-value="value"> <a [routerLink]="['/devicedtls',r ...

Creating a dynamic form with Angular 7 using ngFor and ngModel, incorporating validation through ngFrom attribute

I am currently working on developing an Angular input form that resembles a table. Here is my current approach: HTML: <form (ngSubmit)="doSomething()"> <table> <thead> <tr>First Name</tr> <tr>Last ...

Issue with the deprecated router package in Angular 2 rc3

Welcome Angular 2 rc.3! After following the instructions in the 5 Min Quickstart and using project.json to configure my project, I encountered an error when running npm install: No compatible version found: @angular/<a href="/cdn-cgi/l/email-protectio ...

What are the steps to implement Owl Carousel 2 in Angular2?

Struggling to integrate Owl Carousel 2 into my Angular2 project, I have hit a roadblock. Could someone kindly provide a detailed walkthrough on how to effectively configure it? ...