Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue where disabled or readonly inputs are not being submitted by angular forms – specifically the exchange rate and target amount (in btc).

Attempted both template-driven and data-driven approaches without success. Values are not logged to console unless disabled/readonly properties are removed from inputs.

Appreciate any assistance on this. Below is the code snippet:

component.ts

// Component logic here
// Code commented out for brevity 

In the code provided, note that the data-driven approach is used only in the form submission function.

html:

<form (ngSubmit)="onSub(f)" #f="ngForm">
          <div class="form-group">
            // HTML input fields here
          </div>
          <button md-raised-button type="submit" color="primary" class="btn-w-md">Confirm</button><div class="divider divider-sm"></div>
        </form>

Thanks again!

EDIT!!!:

data driven html:

<form [formGroup]="myForm2" (ngSubmit)="onSub()">
              <div class="form-group">
                // Data-driven form fields here
              </div>
              <button md-raised-button type="submit" color="primary" class="btn-w-md">Confirm</button><div class="divider divider-sm"></div>
            </form>

Answer №1

If you're looking to retrieve all form values, including the disabled ones, you can utilize getRawValue().

For example, if your form is structured like this:

this.myForm2 = this.fb.group({
  email: ['', Validators.email],
  clpmount: ['', Validators.required],
  btcmount: [{value: '', disabled: true}],
  ....
});

You can simply use

this.myForm2.getRawValue()

This will provide you with the value of btcmount in the above scenario.

UPDATE:

After reviewing the template... In reactive forms, Angular does not recognize the value and [value] bindings. To work around this issue, it's recommended to utilize one-way binding by using [ngModel]="baseAmount" for your field clpAmount. Why? The ngModel directive is not part of the ReactiveFormsModule, indicating that they are not intended to be used together even though it's not explicitly stated in the documentation. Using [(ngModel)] concurrently could result in two conflicting bindings, potentially causing complications.

[ngModel] offers a better approach as Angular strictly binds the value from TypeScript to the template without concerning itself with subsequent actions. Despite reactive forms disregarding value, it still acknowledges ngModel, making it suitable for this situation! Thus, replace [value] with [ngModel]:

<input mdInput  formControlName="btcmount" [ngModel]="targetAmount | number:'1.8-8'">

<input mdInput formControlName="rate" placeholder="Tasa de cambio" [ngModel]="exchangeRate | number:'1.0-0'">

By making this adjustment, all values will be accessible when utilizing getRawValue() :)

Answer №2

If you need to retrieve all form values

Update this function

onSub() {
 console.log(this.info);
}

to

import { NgForm } from '@angular/forms';

onSub(formData : NgForm) {
 console.log(formData.value);
}

Issue with Readonly/Disabled input submission in Angular

Disabled inputs will not be submitted However, Readonly inputs will always be included in the submitted form

The problem lies within your code, not Angular itself.

Answer №3

Building on Vivek's explanation, when using a reactive form, you can achieve it in the following way:

this.myForm = this.fb.group({
      email: ['', Validators.email],
      amount: ['', Validators.required],
      btcAmount: [''],
      rate: [''],
      description: ['']
});

Additionally, you can handle the form submission like this:

public onSubmit() {
  console.log(this.myForm.value);
}

Alternatively, for tracking changes:

ngOnInit() {
  ...
  this.form.valueChanges.subscribe(value => console.log(value));
}

The key is to extract data directly from the form itself rather than relying on the model. This principle applies to both reactive and model-driven forms as described by Vivek (passing in the form instead of the model).

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

Utilizing Pipes within a Method in Angular 2 along with Dependency Injection triggers an "Insufficient Number of Arguments" error

I am searching for a solution to incorporate a custom pipe into my class. The custom pipe itself ( referenced from this source, many thanks ) involves injecting a dependency (the DomSanitizationService). import { Pipe, Inject, Injectable } from '@ang ...

Tips for generating search engine optimized URLs with category/subcategories/article slug in an Angular application

Currently, I am utilizing Angular 8 Version to develop a news application. My objective is to showcase the link in the following format: www.domain.com/category/category/title and www.domain.com/category. Can you guide me on how to accomplish this task? T ...

What is the best way to configure distinct proxy and backend API URLs for development and production environments?

My goal is to seamlessly link an Angular / C# Web Api project on localhost while developing. For this, I typically use the following URL in the Angular app: http://localhost:5000/api/something However, this setup does not work once deployed. Ideally, I w ...

Is it Angular's responsibility to automatically remove template event listeners?

Within my template, I have incorporated click event listeners: <a class="link-component" href="{{displayURL}}" (click)="handleClick($event)"> I am aware that I could alternatively utilize HostListeners or Renderer2 in the following manner: this. ...

Tips for implementing loading functionality with Interceptor in Angular version 17

I am attempting to implement an interceptor in the latest version of Angular 17. export const loadingInterceptor: HttpInterceptorFn = (req, next,) => { const loadingService = inject(LoadingService); loadingService.show(); return next(req).pipe( finaliz ...

Update the router URL without switching pages, yet still record it in the browser history

One of the features on my search page allows users to perform searches and view results. Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature. In my ngOnInit meth ...

Typescript declaration for a Record containing a specified set of fields

I am working on the code below: type MyDict = { [k: string]: unknown; }; function fn<T extends MyDict>(items: T) { const functionDict: { [k: string]: (val: keyof T) => void } = Object.fromEntries( Object.keys(items).map((key: keyof T) =&g ...

Difficulty in utilizing Jasmine spy on Capacitor Plugin within an Ionic application

I am in the process of setting up a unit test for an Ionic App. Here is the snippet from my specs: it('should not affect status bar on browser', async () => { spyOn(Plugins.StatusBar, 'setStyle'); const service: AppService = Te ...

What is the best way to retrieve the value of this object?

In my project, I am utilizing Angular 8 to extract data from a radio input. However, when I transmit this data to Node.js and then to a MongoDB database, it is not being properly registered. The entry in the database collection appears as follows: "__v" : ...

Cannot access assets: Angular 8 deployment on Tomcat 9.0.30 is prevented due to an invalid MIME type ("text/html")

I am currently working on a project that involves an angular 8 user interface and a springboot java backend. The project is structured as a multi module project, with the angular portion in a separate module. To build the angular code into a single executa ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

Combining marker, circle, and polygon layers within an Angular 5 environment

I am working on a project where I have an array of places that are being displayed in both a table and a map. Each element in the table is represented by a marker, and either a circle or polygon. When an element is selected from the table, the marker icon ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

A guide on activating the button once a user chooses an option from the dropdown menu in Ionic

I'm currently developing an Ionic Ecommerce app where I display products with their sizes. However, I'm facing an issue - I want to restrict users from adding the product to the cart without selecting a size first, but I'm struggling to impl ...

typescript persist zustand: typing your store

Running a simple store interface CartState { cart: { [id: string]: CartDto }; addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void; removeItem: (id: string) => void; reset: () => void; } export const use ...

Transitioning from TSLint to ESLint in Angular across several projects leads to ng lint command freezing

After successfully migrating one of my Angular 10 apps using a single project from TSLint to ESLint, following the steps outlined by Angular ESLint, I encountered a problem when trying to migrate an Angular 10 app with multiple projects located in the &apo ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...