Troubleshooting disabled Form Control in Angular 16 Reactive Form Bug

I am currently working on developing a dynamic form using Angular 16. My objective is to disable one of the input fields when a checkbox is checked to prevent data entry. However, the code I have implemented so far does not seem to be working as expected. Can someone provide assistance? When I remove the formControlName, the field gets disabled but then I am unable to capture the user input.

<form [formGroup]="personelForm">
  <div class="row">
    <mat-checkbox class="example-margin" formControlName="isCheck">Not Phone</mat-checkbox> <br>
  </div>

  <div class="row">

    <mat-form-field style="margin-right: 10px;">
      <mat-label>Phone</mat-label>
      <input matInput type="number" formControlName="phone" 
        [disabled]="personelForm.get('isCheck').value">
    </mat-form-field>


    <mat-form-field style=" margin-right: 10px;">
      <mat-label>Name</mat-label>
      <input matInput type="text" formControlName="name">
    </mat-form-field>

    <mat-form-field style="margin-right: 10px;">
      <mat-label>Surname</mat-label>
      <input matInput type="text" formControlName="surname" >
    </mat-form-field>

  </div>

</form>
personelForm: FormGroup;

constructor(private fb: FormBuilder){}
reloadForm() {
  this.personelForm = this.fb.group({
    isCheck:  new FormControl(false),
    phone: new FormControl(0),
    name:  new FormControl(''),
    surname:  new FormControl('')
  });
}

ngOnInit() {
  this.reloadForm();
}

Answer №1

It is recommended to use [attr.disabled] (Attribute binding) instead of [disabled].

 <input
  matInput
  type="number"
  formControlName="phone"
  [attr.disabled]="personelForm.get('isCheck')!.value"
/>

Another approach is to subscribe to the isCheck control's valueChanges observable and dynamically enable/disable the phone control in the component.

this.personelForm.get('isCheck')!.valueChanges.subscribe((isCheck) => {
  if (isCheck) this.personelForm.get('phone')!.disable();
  else this.personelForm.get('phone')!.enable();
});

Check out the demo on StackBlitz

Answer №2

One approach could be to consider utilizing an alternative solution provided by Yong Shun, with a direct access to the control property in order to prevent unnecessary non-null assertions:

this.personelForm.controls['isCheck'].valueChanges.subscribe((isCheck) => {
  if (isCheck) {
    this.personelForm.controls['phone'].disable();
    this.personelForm.controls['phone'].reset();
  } else {
    this.personelForm.controls['phone'].enable();
  }
});

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

The missing properties in the TS Type are as follows:

Currently working with Angular 7.x.x and TypeScript version 3.2.4. I have defined two TypeScript interfaces where one extends the other: Main interface: export interface Result { var1: string; var2: number; var3: boolean; } The second ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Styling only for Angular 2 Components

How can component scoped styles be used to style elements differently based on their location within the site while still maintaining style scoping? For example, when using a "heart like" item created in this course, how can padding be added specifically i ...

When using Google Chrome, you may encounter an error message stating that the 'Access-Control-Allow-Origin' header in the response cannot be set to a wildcard '*' even when a specific URL is specified

In my web application, I've utilized Angular 9 for the frontend and nodejs for the backend. The CORS middleware setup in my Express JS server is as follows: const corsOptions = { origin: [ "http://localhost:4200", ...

Using a Fake Timer to test the setTimeout function for a class method is not possible

One way to test setTimeout with a normal function is by using the following code: function doAsync() { setTimeout(doAsync, 1000) } jest.useFakeTimers() test("setTimeout with function", async () => { doAsync() jest.advanceTimersByTime(2 ...

Resize the p-accordion within a p-splitter using PrimeNG programmatically

Please find the code for my component below: In this component, I have a p-splitter that is divided into 3 sections. Each section contains a p-accordion, which in turn includes a p-table. <div class="card w-full"> <p-splitter [p ...

Tips for successfully incorporating a date parameter in an Angular 8 GET request

Can anyone guide me on how to correctly pass a date in an Angular 8 $http Get request? I'm looking to achieve something like this: public getCalendarData(Date): any { let myResponse = this.http.get(`${environment.BASE_URL}/getCalendarData` + & ...

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({ ...

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Is it necessary for Angular to wait for the template to update before moving on to perform calculations

My goal is to animate smoothly from an auto height to zero and back. When using jQuery, I would have to manually calculate the height of the auto container, set it as a fixed height, then change it to zero allowing css transitions to take over. To revert b ...

Tips for incorporating socket.io-stream in Angular applications

How can I integrate socket.io-stream into an Angular application? While we can easily use socket.io-stream in a web client with Browserify (https://github.com/nkzawa/socket.io-stream?tab=readme-ov-file#browser), it seems to not work as smoothly in Angular. ...

React Native bottom tab navigator not changing between tabs

Hi, I'm new to React Native and I think I might have a structural issue because I can't figure out what I'm doing wrong. I'm trying to create 4 tabs, but when I click on each tab, it doesn't take me to the next page. Nothing happe ...

Unable to dynamically load a script located in the node_modules directory

This particular approach is my go-to method for loading scripts dynamically. import {Injectable} from "@angular/core"; import {ScriptStore} from "./script.store"; declare var document: any; @Injectable() export class ScriptService { private scripts: an ...

The combination of TypeScript 2.6 and material-ui 1.0.0-beta.24's withStyles with react-router withRouter is resulting in the error message: "Property 'classes' is missing in type."

Using the high order components withStyles and withRouter together has been a smooth process so far. However, after upgrading to the latest versions of these components, an error occurred. Learn more about higher-order components List of packages used: ...

NextJS Typescript Player

Encountering an issue during the build process, specifically with the error in audioRef.current.play(). The error message indicates that there is no play function available. I attempted to use an interface but it seems to not accept boolean values. Could ...

What is the best way to choose an ID that changes based on the index position?

Let me clarify my point first. Within a dropdown menu, there are 5 buttons - 2 with fixed IDs and 3 that can be altered through a separate micro service (such as when changing break types). The IDs for these 3 buttons are dynamically generated based on th ...

Vite encounters issues resolving .d.ts files when importing

I'm having trouble importing a type from my type.d.ts file import type { StateDefinition } from '../type' When using Vite, it can't find the file and throws an error https://i.sstatic.net/buZ14.png To resolve this, I tried adding the ...

Angular 7 data update causing issues with Bootstrap carousel functionality

I am encountering an issue with the Bootstrap carousel in my Angular 7 application. The carousel contains data that needs to be updated at regular intervals. Initially, the carousel works as expected. However, once the HTTP service updates the array of sli ...

Storing and Retrieving User Identifiers in Next.js

Currently, I am developing a project using Next.js and I have the requirement to securely store the userId once a user logs in. This unique identifier is crucial for accessing personalized user data and creating dynamic URLs for the user profile menu. The ...

Improving efficiency with batch processing in angular-apollo-client

How can I enable batching in the Angular Apollo client? I'm having trouble passing the shouldbatch=true parameter to the constructor of the Angular Client. ...