Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms.

Let's take a look at my code first.

File Name: home-page.component.html

<form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)">

    ...

    <div class="input-field col s12">
        <select formControlName="pasteSyntax">
            <option *ngFor="let choices of pasteSyntaxChoices" [value]="choices.value">{{ choices.text }}</option>
        </select>
        <label>Syntax Highlighting</label>
    </div>

    ...

</form>

File Name: home-page.component.ts

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

@Component({
    selector: 'app-home-page',
    templateUrl: './home-page.component.html',
    styleUrls: ['./home-page.component.css']
})

export class HomePageComponent implements OnInit {

    rForm: FormGroup;
    paste: any;

    ...

    pasteSyntax: string = '';

    ...

    pasteSyntaxChoices = [
        { value: "plain", text: "Plain Text" },
        { value: "html", text: "HTML" },
        { value: "css", text: "CSS" },
        { value: "js", text: "JavaScript" },
        { value: "php", text: "PHP" },
        { value: "perl", text: "Perl" },
        { value: "go", text: "Go (Golang)" }
    ];

    constructor(private fb: FormBuilder) {
        this.rForm = fb.group({

            ...

            'pasteSyntax': [null, Validators.required]

            ...

        });
    }

    addPaste(paste) {

        ...

        this.pasteSyntax = paste.syntax;

        ...

        console.log(paste);
    }

    ngOnInit() {}

}

Additional Information:

@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
core-js: 2.4.1
rxjs: 5.4.2
zone.js: 0.8.14

Expected Output (From console.log):

Object
    pasteSyntax: "plain"

Current Output (From console.log):

Object
    pasteSyntax: null

Can someone please guide me on where I made a mistake or used the wrong syntax?

Answer №1

The issue lies in this specific line within your addPaste method:

this.pasteSyntax = paste.syntax;

To rectify this, it should read as follows:

this.pasteSyntax = paste.pasteSyntax;

Furthermore, as Nilandri pointed out, there is no need for an additional variable. You can directly access the value from your form template or print the pasteSyntax property by submitting the form with rForm.value as a parameter:

addPaste(value) {
  console.log(value.pasteSyntax);
  console.log(this.rForm.get('pasteSyntax').value);
  // or
  console.log(this.rForm.controls.pasteSyntax.value)
}

View Demo

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

Concentrate on a specific input within a list of inputs that are generated dynamically

My list contains dynamically generated inputs. input --> onClick new Input beneath [dynamically added]input input How can I focus on just the dynamically added input? The input has the textInput reference. This code partially achieves it: componentW ...

What is the solution for the error message "TypeError: app.use() is seeking a middleware function"?

I am a beginner in Node.js and have encountered an issue in my passport.js or signupLogin.js file with the error message, app.use() requires a middleware function that I am struggling to resolve. I suspect it may be related to the signupLogin route, as th ...

Error message received while converting webm video to images using Kagami/ffmpeg.js: Unable to locate an appropriate output format for '%04d.jpg'

These are the current versions: node v12.9.1, npm 6.10.2, [email protected] Repository: https://github.com/Kagami/ffmpeg.js The code in decode.js looks like this: const fs = require('fs'); const ffmpeg = require('ffmpeg.js'); c ...

Having trouble getting the Next.js Custom Server to function properly with Firebase

I have deployed my Next.js App on Firebase and I am using a custom server (server.ts) to launch the app (node src/server.ts). The code for the server.ts file along with firebaseFunctions.js is provided below. The server.ts file works fine locally, which ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

Limiting the display to only a portion of the document in Monaco Editor

Is there a way to display only a specific portion of a document, or in the case of Monaco, a model, while still maintaining intellisense for the entire document? I am looking to enable users to edit only certain sections of a document, yet still have acce ...

What is causing the breakdown in communication between my server and client?

While utilizing React and an Express server for the backend, I am facing an issue where my API call to server.js is not going through. The React client is running on port 3001 and the server on port 3002. The fetch code in CreateAccount.js is as follows: ...

Hello, I am looking for a way to maintain a user's active session when transitioning between different Angular applications without constantly prompting them to login. Can you help me

After logging in with my credentials, the session starts. However, if the user does not have an administrator role, I need to redirect them to another application. The challenge is maintaining the active session without requiring the user to log in again ...

Adding an object dynamically to a JSON array: Step-by-step guide

I am facing a challenge trying to dynamically add an attribute inside each object within my JSON array. Unfortunately, I have not been successful in achieving this as my new object is being appended at the end of the JSON which is not the desired outcome. ...

Converting JSON data retrieved from a URL into HTML format

I have a JSON output from a URL that I need to format into html. The structure of the JSON data is as follows: prtg-version "xxxxxxx" treesize 0 channels 0 name "Downtime" name_raw "Downtime" lastvalue "" lastvalue_raw "" 1 name ...

What is the method for binding context on a click event in Vue?

Can't access context function on click in Vue Example HTML with click function: <li v-on:click="itemClick($event, this)"></li> My Vue.js code snippet: var app = new Vue({ el: '#mainApp', methods: { ite ...

Sending information in Json format back to an Ajax request

I have a method in the Model-View-Controller (MVC) framework where I submit data and expect to receive some processed data back. The MVC method I am posting to returns JSON data. [HttpPost] public JsonResult GetCalculateAmortizationSchedule() { var da ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

Angular allows for routing two distinct paths to separate components located within the same lazily loaded submodule

There are two paths available: /a and /b Both routes lead to the same child module in the parent module: // app-routing.module.ts { path: 'a', loadChildren: () => import('./m-child/m-child.module').then(m => m.ChildModu ...

What is the most effective method for displaying indicators for in-flight requests in rxjs without causing side effects?

What is the best way to display a loading indicator for an ongoing request using RXJS (along with Angular2+) without causing side effects in the pipe() function? I've brainstormed some options. Is there a recommended approach or a better alternative? ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Using Backbone.js to dynamically filter a collection when a user clicks a specific element

update added more details about my progress so far. I'm currently in the process of developing an app that showcases the gists of members belonging to a specific organization, drawing inspiration from bl.ocks.org. My goal is to enable users to click ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...