How to disable button if variable are empty ?

Forums AngularHow to disable button if variable are empty ?
Staff asked 2 years ago

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

To disable a button if a variable is empty in Angular, you can use property binding and template expressions. Here’s an example:

  1. In your component class, declare the variable that you want to check for emptiness. For example:
export class MyComponent {
  myVariable: string = '';
}

  1. In your component template, add a disabled attribute binding to the button, and bind it to a template expression that checks if the variable is empty. For example:
<button [disabled]="!myVariable" (click)="onClick()">My Button</button>

Here, the disabled attribute binding is bound to a template expression that checks if the myVariable variable is falsy (empty, null, or undefined). If the variable is falsy, the button will be disabled; otherwise, it will be enabled.

  1. In your component class, define the onClick method that will be called when the button is clicked. For example:
export class MyComponent {
  myVariable: string = '';

  onClick() {
    console.log('Button clicked');
  }
}

Here, the onClick method is defined to log a message to the console when the button is clicked.

By using property binding and template expressions like this, you can disable a button if a variable is empty in your Angular application.

Subscribe

Select Categories