To disable a button after clicking in Angular, you can bind the disabled
property to a flag(for eg. isClicked) in your ts file. Keep this flag false
by default and set it to true
whenever the button is clicked.
To keep track of whether the button is clicked or not, you have to add an event handler to the button.
Now, whenever someone clicks on the button, the flag becomes true and therefore the button becomes disabled instantly as it is bound with the disabled
property.
<button [disabled]="isClicked" (click)="doSomething(); isClicked=true;">Click Me</button>
If your ts file you have to declare the isClicked
flag and the click event handler method doSomething():
isClicked: boolean = false; doSomething(){ // Write your stuff here }
You can also set the isClicked
flag to true
inside your doSomething() click event handler method. This will also disable the button after clicking.
Here is the updated template file:
<button [disabled]="isClicked" (click)="doSomething();">Click Me</button>
And here is the updated doSomething()
function:
isClicked: boolean = false; doSomething(){ this.isClicked = true; // Write your stuff here }
Solution 2:
An alternative solution could be to pass the $event
inside the click event handler function and then set the button’s disabled
property to true using the event.target.disabled
:
Here is what you need to add to your template file:
<button (click)="doSomething($event);">Click Me</button>
And here is the updated doSomething() function:
doSomething(event:any){ event.target.disabled = true; // Write your stuff here }