Disable Angular FormControl

By Arvind Rai, January 10, 2021
On this page we will learn how to disable FormControl in Angular application. We can disable a FormControl by passing disabled attribute while instantiating it. We can use disable() and enable() method of FormControl. We can also call disable/enable function at runtime by using control[action]() method of FormControl. We need to pass action as 'disable' or 'enable'. We can also use [disabled]="true" binding to disable a form control.
Now let us discuss the examples to use all above approach to disable form controls step-by-step.

Technologies Used

Find the technologies being used in our example.
1. Angular 11.0.3
2. Node.js 12.5.0
3. NPM 6.9.0

Passing disabled in FormControl

To disable a FormControl, we pass disabled attribute to it as following.
company = new FormControl({value:"", disabled: true}); 
Find the disabled attribute with validations in FormControl.
company = new FormControl({value:"Krishna", disabled: true}, [Validators.required]); 

Using disable() and enable() method of FormControl

A FormControl can be disabled and enabled using its disable() and enable() method respectively.
Find the component code.
cityName = new FormControl();
cityNameDisable() {
  this.cityName.disable();
}    
cityNameEnable() {
  this.cityName.enable();
} 
Find the HTML template code.
<input [formControl]="cityName"> 
<button (click)="cityNameDisable()">Disable</button>
<button (click)="cityNameEnable()">Enable</button><br/> 

Creating Directive to Enable/Disable Control

Find the directive to enable/disable control.
enable-disable-directive.ts
import { NgControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[enableDisable]'
})
export class EnableDisableDirective {
  @Input() set enableDisable(action: string) {
    this.ngControl.control[action]();
  }
  constructor(private ngControl: NgControl) {
  }
} 
a. Below code will return disable() function.
ngControl.control['disable']() 
b. Below code will return enable() function.
ngControl.control['enable']() 
Find the HTML code to use this directive.
<input [formControl]="countryName" 
	   [enableDisable]="cnAction">
<button (click)="cnAction = 'disable'">Disable</button>
<button (click)="cnAction = 'enable'">Enable</button> 

Using [disable] Binding

We can disable a control using [disabled]="true" binding.
<input [formControl]="company" [disabled]="true"> 
We can also disable control using [attr.disabled]="true".
<input [formControl]="company" [attr.disabled]="true"> 
Angular does not suggest to use [disabled]="true" binding to disable a control. Using [disabled]="true" gives us a message in browser console as following.
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.

Example:
form = new FormGroup({
  first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
  last: new FormControl('Drew', Validators.required)
}); 

Complete Example

Here we will provide complete code of our example. The code for EnableDisableDirective is given above in the article. Find the other files of our example.
reactive-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-reactive-form',
  templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {
  company = new FormControl({value:"", disabled: true});
  cityName = new FormControl();
  state = new FormControl();
  countryName = new FormControl();
  cityNameDisable() {
    this.cityName.disable();
  }    
  cityNameEnable() {
    this.cityName.enable();
  }
  cnAction = "enable";
  userForm: FormGroup;
  ageAction = "enable";
  constructor(private formBuilder: FormBuilder) {
  }
  ngOnInit() {
    this.userForm = this.formBuilder.group({
      name: [{value:"Mahesh", disabled: true}, [Validators.required]],
      age: ''
    });
  }
  onFormSubmit() {
    console.log(this.userForm.value);
    this.userForm.reset();
  }
} 
reactive-form.component.html
<input [formControl]="company"> <br/>
<!--input [formControl]="company" [disabled]="true"-->
<input [formControl]="state" [attr.disabled]="true"> <br/>
<input [formControl]="cityName"> 
<button (click)="cityNameDisable()">Disable</button>
<button (click)="cityNameEnable()">Enable</button><br/>

<input [formControl]="countryName" 
	   [enableDisable]="cnAction">
<button (click)="cnAction = 'disable'">Disable</button>
<button (click)="cnAction = 'enable'">Enable</button>	   

<h3>User Form</h3>
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
	<table>
		<tr>
			<td>Name: </td>
			<td>
				<input formControlName="name">
			</td>
		</tr>		
		<tr>
			<td>age: </td>
			<td>
				<input formControlName="age" [enableDisable]="ageAction">
				<button (click)="ageAction = 'disable'">Disable</button>
				<button (click)="ageAction = 'enable'">Enable</button>	
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<button>Submit</button>
			</td>
		</tr>
	</table>
</form> 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
				<app-reactive-form></app-reactive-form>
             `
})
export class AppComponent {
} 
styles.css
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}
.error {
    color: red;
}
.success {
    color: green;
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ReactiveFormComponent } from './reactive-form.component';
import { EnableDisableDirective } from './enable-disable-directive';

@NgModule({
  imports: [
      BrowserModule,
      ReactiveFormsModule,
  ],
  declarations: [
      AppComponent,
      ReactiveFormComponent,
      EnableDisableDirective
  ],
  providers: [
  ],
  bootstrap: [
      AppComponent
  ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
Disable Angular FormControl

Reference

Angular FormControl

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us