Is there a way to track all Angular form controls that have switched between being enabled and disabled?

Summary: When a FormGroup contains a nested FormControl that changes from disabled to enabled or vice versa, the FormGroup is not marked as dirty.

Details: How can you identify all form controls within a FormGroup that have switched between being enabled and disabled?

The example on this Stackblitz shows that properties like pristine, dirty, touched, and untouched remain unchanged when a control transitions from enabled to disabled or vice versa.

export class AppComponent implements OnInit {
  person: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.person = this.fb.group({
      name: this.fb.control(''),
      age: this.fb.control(100),
    });
  }
}

In the TypeScript snippet above, a single FormGroup called 'person' with two FormControls (name and age) is defined.

The HTML code below allows toggling the 'name' control between enabled and disabled states by clicking buttons. The output includes various properties.

<form [formGroup]="person">
    <input type="text" placeholder="Name" formControlName="name">
    <button (click)="person.controls['name'].disable()">Disable</button>
    <button (click)="person.controls['name'].enable()">Enable</button>
    <br />
    <br />
    <input type="text" placeholder="Age" formControlName="age">
</form>

<pre>{{person.value | json}}</pre>

disabled: {{ person.disabled }}<br />
pristine: {{ person.pristine }}<br />
dirty: {{ person.dirty }}<br />
touched: {{ person.touched }}<br />
untouched: {{ person.untouched }}<br />

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

I expected it to be straightforward to detect when a control becomes:

  • enabled after being disabled
  • disabled after being enabled

Unlike other properties like pristine, dirty, touched, and untouched, the enabled/disabled state of a control seems temporary.

It appears there is no specific property in a FormGroup indicating whether child controls have changed from their original enabled/disabled state. The FormGroup remains pristine and untouched.

Suggestions to use statusChanges only provide four validation status values (VALID, INVALID, PENDING, DISABLED), making it challenging to map these statuses to specific controls and determine if they have transitioned between enabled and disabled. Another Stackblitz demonstrates this issue.

EDIT:

I have raised a bug report for the observed behavior: FormGroup not marked as dirty when nested FormControl switches between disabled and enabled states.

Answer №1

If you're looking to monitor changes in control status, consider keeping an ear out for the disabled attribute.

Check out the details here: https://angular.io/api/forms/AbstractControl#status

For receiving updates on status changes, take a look at: https://angular.io/api/forms/AbstractControl#statusChanges

Note that there is a method specifically designed for this task, known as registerOnDisabledChange. Learn more about it here: https://angular.io/api/forms/FormControl#registerOnDisabledChange

Feel free to explore a modified version of your code on StackBlitz: https://stackblitz.com/edit/formbuilder-soydhk

If you require control-level monitoring, don't hesitate to set up a listener to capture and aggregate the necessary data.

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

Having trouble locating the module for my custom TypeScript module

Exciting news! I have recently released a new TypeScript-based module on the NPM registry, called ooafs. However, when attempting to install and import it into another TypeScript project, an error pops up in VSCode stating: Cannot find module 'ooafs&a ...

In Angular, the data is displayed in the console but is not visible in the application

After successfully fetching data from the backend and seeing it displayed in the console https://i.sstatic.net/eRjli.png However, there seems to be an issue with rendering the data even though it is being recognized. Here's the relevant code snippet: ...

Two storage locations exhibit distinct behavior when it comes to the favicon

After moving my repository to a new origin and pulling it into a different directory on my computer, I encountered an issue with my .NET Core API and Angular client. The problem is that the new instance of the repository, after being built, does not disp ...

Having trouble resolving the npm ERR with @angular-devkit/[email protected]? Found the solution to fixing it by checking out @angular/[email protected] instead

When I try to update the local Angular CLI version, I keep encountering an error with this command: npm uninstall --save-dev angular-cli. (following instructions from this source) npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ER ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

I am configuring Jest in my Vite and TypeScript-powered React project

I am having trouble with the relative path of the file I imported in App.test.tsx. It keeps showing me this error message: Cannot find module '@/components/items/card.tsx' from 'src/__tests__/App.test.tsx' Below is the code snippet: // ...

Utilize a single API to save data to the database and upload files simultaneously

I am looking to streamline the process of saving data in a database and uploading a file using a single API endpoint. I am working with Angular and Spring frameworks: The challenge I am facing is that I currently have two functions in Angular and two func ...

Avoid obtaining cookies within the TRPC environment

Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie ...

Getter and setter methods in Angular Typescript are returning undefined values

I am facing a challenge in my Angular project where I need a property within a class to return specific fields in an object. Although I have implemented this successfully in .Net before, I am encountering an issue with getting an "Undefined" value returned ...

Looking to retrieve the smallest amount of array sets in Angular4

I'm currently developing an Angular 4 application and facing an issue with a function I'm trying to write. The goal is to extract the minimum and maximum numbers from three array objects. The yAxisData object consists of three yaxis array objects ...

Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code: The issue I am facing is that it only copies the URL on the second attempt and then st ...

When attempting to upload an image in Angular 9, I am receiving an empty object as a result

I am encountering issues with my formData resulting in an empty object or a bad request error when trying to post a file upload to the server. The problem seems to originate from the service where FormData is being created, as it sends the formData over as ...

Resolving search box setup problem in PrimeNG dataView

I am working on integrating p-dataView with Angular 5 but encountering an error Cannot read property 'split' of undefined at DataView.filter Despite checking the documentation, I have been unable to find a solution to this issue. It seems lik ...

Struggling to implement the Pick utility type alongside the React useState hook

Can anyone explain why I am unable to utilize the Pick utility type in order to select a property from my interface and apply it to type my component's state? This is what my interface looks like: export interface IBooking { ... propertyId: strin ...

Unresolved peer dependencies in Angular 2

I recently set up an angular2 project using CLI, and my package.json file is structured as shown below: { "name": "thesis-proto", "version": "0.0.0", "license": "MIT", "angular-cli": {}, "scripts": { "ng": "ng", "start": "ng serve", ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

Angular's observable function is not providing a complete response

In my Angular component, I have a function that is called from a template. This function returns an Observable of type string, but unfortunately it only returns the `data` variable. How can I modify it to return `dateNew[0] + " de " + data + " de "+ dateNe ...

A guide on incorporating ngFor with the flipping card feature in Angular

I am attempting to use ngfor to create some flip cards. However, the cards are not starting a new line and are overlapping in the first line. I have a total of 4 cards, but the 4th card is overlapping with the 1st card. I believe this issue is related to t ...