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 = '';
}