by Sai gowtham

How to disable the button in Angular

In this tutorial, we are going to learn about how to disable or enable the HTML button element in an angular app.

Disabling the button

We can disable a button by passing the boolean value true to the disabled attribute.

app.component.html
<button [disabled]="isDisabled">Subscribe</button>
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  isDisabled = true;
}

To enable it back, we need to set the isDisabled property value to false.

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  isDisabled = false;
}

Disabling the button when input field is empty

We can also disable the button conditionally when an input field value is empty and enable it back if it has some data.

Example:

app.component.html
<input type="email" placeholder="Email" [(ngmodel)]="email" />
<button [disabled]="!email.length">Subscribe</button>
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  email = '';
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course