Angular: Ensure that form control is disabled correctly to preserve the value for later retrieval

Here is my angular reactive form setup:

  zoneEntryForm = new FormGroup({
    code: new FormControl(''),
    zonename: new FormControl(''),
  });

The output I'm getting from this code is:

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.zoneEntryForm.value);
  }

output

https://i.sstatic.net/AxHc8.png

[Note: code is a number, zone is a string]

Now, I need to read the value from both the code and zone, but I want the code field to be disabled. The code is retrieved from the database and the user won't input it. Later, I need to send this code and zone name somewhere else.

Both fields should be blank by default.

Here are my attempts:

Attempt 1:

  zoneEntryForm = new FormGroup({
    code: new FormControl({value: '', disabled: true}),
    zonename: new FormControl(''),
  });

output: https://i.sstatic.net/SJ2eT.png

As you can see, the code field is no longer being read by onSubmit

Attempt 2:

  zoneEntryForm = new FormGroup({
    code: new FormControl({disabled: true}),
    zonename: new FormControl(''),
  });

output :

https://i.sstatic.net/A1ky2.png

Now, my default blank value is gone

So, how can I make the code field disabled and still be able to read from it properly at the same time?

Answer №1

If you want to retrieve the value of a disabled FormControl, you can use the getRawValue() method on the FormGroup

this.zoneEntryForm.getRawValue()

Check out this stackblitz for a working example

Typescript Code

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  zoneEntryForm = new FormGroup({
    code: new FormControl({
      value: '1234',
      disabled: true
    }),
    zonename: new FormControl('testzone'),
  });

  ngOnInit() {
    console.log(this.zoneEntryForm.getRawValue());
    console.log(this.zoneEntryForm.getRawValue().code);
    console.log(this.zoneEntryForm.getRawValue().zonename);
  }
}

Answer №2

To set a default value for code and retrieve it upon submission, follow a similar method of assigning a predefined value for code. If the value is dependent on an action, you can declare a public variable and assign it accordingly.

this.codeValue = 'testCode'; //or assign anywhere based on condition 
zoneEntryForm = new FormGroup({
    code: new FormControl({value: this.codeValue, disabled: true}),
    zonename: new FormControl(''),
  });

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

"Upon studying the Reflect-metadata index.d.ts file, I find myself perplexed by the variances in

While utilizing the reflect-metadata package, I encountered this particular type. However, I am uncertain about its meaning and function signature. function metadata(metadataKey: any, metadataValue: any): { (target: Function): void; ( ...

Refreshing the browser causes Angular route to display raw JSON data

I have been working on a MEAN stack application and I have set up a proxy configuration for development purposes. Everything seems to be in order as I am able to successfully call an API from Angular/Node. However, the issue arises when I refresh the brows ...

Remove the hyphen from a user input field using Angular 2 and reactive forms

After deleting data from input fields, I am facing an issue where the dynamic addition of a hyphen prevents the input field from being cleared. Is there a solution to this problem? How can I delete or clear the input fields effectively? Although I have ad ...

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

Closing Popover Instance from another Component (Ionic, Typescript)

I've been dealing with an issue where a function that I imported from another class isn't getting called and the parser isn't recognizing it. The Popover in my code also can't be closed. I've tried various similar solutions, but no ...

Retrieve all data values from a form using the ngModel directive within an Angular application

I am having trouble retrieving all the values from a form using ngModel. I am only able to get the values from the first text box and not the ones added after clicking the button. For example, you can check this StackBlitz link. Here is the HTML code sni ...

Encountering issues with building NX Angular Storybook

Following the execution of nx migrate, our Storybook stories are encountering build errors such as: Error: Cannot find module '@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs' ERR! at Function.Module._resolveFilenam ...

Having trouble with Typescript accurately converting decimal numbers?

I am struggling with formatting decimals in my Typescript class. export myclass { deposit: number; } After converting my web API class to this Typescript class, my decimal amounts lose their additional zero. For example, 1.10 becomes 1.1. I want to keep ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Select a randomly generated number from an array, which dynamically updates every time the browser is refreshed

I recently completed a project in Angular that utilizes the TMDB API. The project is nearly finalized, but I have a desire to implement a change where the background image (backdrop_path) and other elements shift each time the browser is reloaded. Curren ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

Obtain the function's return type without actually executing the function

Consider the following TypeScript function: export const foo = function(){ return { a: 1, b: true, c: 'bar' } }; If I were to import this function into another file: import {foo} from './foobar'; Is there a me ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Having trouble with importing ResizeSensor library into typescript

In my TypeScript app using webpack, I am attempting to utilize css-element-queries/ResizeSensor. After adding the npm package, which includes a .d.ts file, I encountered an issue when writing the following code: new ResizeSensor(element, cb); Instead of ...

Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so f ...

Does anyone know of a custom typeguard that enforces the presence of elements in an array?

I need help creating a custom type guard to determine if an array contains nullable or optional elements. I have defined a helper type called RequiredArray: type RequiredArray<A extends readonly any[]> = A extends [infer P, ...infer R] ? [Non ...

How can I update a value using a specific key in Angular?

So, I have a string value that I need to pass to another function. For instance, if the string is 'eng', I want it to be converted to 'en'. I'm looking for a solution that does not involve using slice or if statements. I attempted ...

By upgrading to Bootstrap 5, the emptyPlaceholder in the file-drag-drop feature is transformed into a sleek gray loading block

Recently, I incorporated the ngx-file-drag-drop ( https://github.com/telebroad/ngx-file-drag-drop) into my project. However, after upgrading from Bootstrap 4 to 5.2.0, I noticed that the placeholder text is now displayed as a grey loading block. How can I ...

Using *ngFor to dynamically update the DOM when an array is modified via ngrx

Currently, I am utilizing *ngFor to present values from an array: [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' } ] In the html: <div *ngFor="let item of (items$ | async); trackBy: trackById;&quo ...