Retrieve the HTML data from a form created with Angular

Here is an example of an Angular form:

<div #myForm [formGroup]="myForm">        
        <select formControlName="productName" class="form-control">
            <option value="">Select</option>
            <option *ngFor="let item of productNames" [value]="item.value"
                [textContent]="item.text"></option>
        </select>
    </div>
    <button (click)="Print()">Print</button>

When I click the button, I want to retrieve the HTML content of the form so that I can use it elsewhere. To achieve this, I tried accessing the innerHtml using the form reference as shown below.

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

@Component({
  selector: 'app-print-form',
  templateUrl: './print-form.component.html',
  styleUrls: ['./print-form.component.css']
})
export class PrintFormComponent implements OnInit {
  myFormGrp: FormGroup;
  productNames:  any[];
  @ViewChild('myForm') myForm: ElementRef<HTMLDivElement>;
  constructor(private formBuilder:FormBuilder) { }

  ngOnInit(): void {
    this.productNames = [
      {text: "aaa", value: "1"},
      {text: "bbb", value: "2"},
      {text: "ccc", value: "3"},
      {text: "ddd", value: "4"}
    ];

    this.myFormGrp = this.formBuilder.group({
      productName: new FormControl({ value: '3', disabled: false })
    });
  }

  Print(): void {
     console.log(this.myForm.nativeElement.innerHTML);
  }

}

However, the innerText does not include the selected value of the dropdown. How can I retrieve the selected values of the form controls?

Answer №1

It appears that you are utilizing reactivform in your code. Be sure to include the (ngSubmit) event listener in this manner:

<form [formGroup]="myForm" (ngSubmit)="print()">

Additionally, remember not to use capital letters for your methods like (print() instead of Print())

To retrieve a value from a form, you can do so like this:

console.log(this.myForm.get('the_value_to_retrieve').value);

For more detailed information on reactive forms in Angular, refer to the official documentation here: https://angular.io/guide/reactive-forms

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

Implementing chance.js in an Angular 4.x Component's ngOnInit() Method

I just started using angular 4.x and I'm trying to load change.js in the ngOnInit() function. I've attempted a few things but nothing seems to be working. Here is the code snippet: This is the code I have so far: import { Component, OnInit, In ...

How can I eliminate the white bar elements from my dropdown menu? Also, seeking guidance on replacing an empty <div> tag in a boolean query

Can anyone help me understand the strange white border around my dropdown menu and guide me on how to remove it? I am currently using DropdownButton from react bootstrap. I have attempted to adjust the CSS with no success. Here is the code I tried: .Navig ...

Make sure to always target a specific DIV element, regardless of whether any of its child divs are

I have a div named "box" nested inside another div called "container." When I click on the box, I am able to retrieve its ID perfectly. However, when I click on the container, I want to obtain the ID of the box instead of the container. Is there a way fo ...

Insert a new item into a current array using Typescript and Angular

-This is my curated list- export const FORMULARLIST: formular[] = [ { id: 1, name: 'Jane Doe', mobileNumber: 987654, secondMobileNumber: 456789, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1bcc0d9ec ...

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

Navigating with Gatsby Link and leveraging TypeScript

I am currently utilizing Gatsby Link with TypeScript and I am looking to pass parameters to a linked component from the source component. The documentation provided by Gatsby states the following: Sometimes you’ll want to pass data from the source pag ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

What are the recommended methods for dealing with arrays that have uniqueItems set to true in OpenAPI?

When I use OpenAPI Generator to generate Angular 12 code from JSON data produced by a Java application, an API model is created as follows: export interface UserDto { roles?: Set<RoleDto>; } The JSON file contains the following information: "U ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

An HTTP request is made with a JSON parameter to invoke a server-side GET function that does not

Having an issue with Angular's get method and unsure why the second server side function is being called instead of the first. Here is my code: var params = { "id": templateCategoryId }; this.http.get(this.appService.baseUrl + 'api/UserL ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

A simple way to retrieve data from Firebase using the unique identifier (ID)

Hello, I am attempting to retrieve the user email for each message. Each message (chat) has a user ID associated with it. I fetch the entire user data using getUser on the *ngIf directive and then display the email address. It works fine and there are no ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

Error in Angular: Trying to access property 'setLng' of a null component variable

Just starting out with Angular and I've come across the error message Cannot read property 'setLng' of null. Can anyone help explain why this is happening? import { Component, OnInit, Input } from '@angular/core'; @Component({ ...

What steps can be taken to resolve the error message "Using 'null' as an index type is not allowed."?

In my TypeScript code, I have a variable called lang declared as a string type value, and a variable called direction declared as an object with two elements. I also have a function that is supposed to return the value of the direction object based on th ...

Steps to reset an Angular material toggle button:1. Locate the

<div id="slider-group" *ngFor="let sliderToggle of sliderToggleGroup"> <div> <mat-slide-toggle (ngModelChange)="updateSlider($event,sliderToggle)" [(ngModel)]="sliderToggle.isChecked"> {{sliderToggle.na ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Error: The update-config.json file could not be located in Protractor

I recently converted my Cucumber tests to TypeScript and started running them with Protractor. When I run the tests from the command-line using the following commands: rimraf cucumber/build && tsc -p cucumber && protractor cucumber/build/p ...