How to disable button if variable are empty ?
Answers (1)
Add AnswerTo disable a button if a variable is empty in Angular, you can use property binding and template expressions. Here’s an example:
- In your component class, declare the variable that you want to check for emptiness. For example:
export class MyComponent { myVariable: string = ''; }
- 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.
- 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.