Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class through ngClass if a disabled button is clicked

I want to be able to add a scss class ("error") to an element, if a [disabled] button is clicked. How do i achieve this? Angular2 disable button the [disabled] attribute is required, so this is not a working solution.

<button [disabled]="!isTermAgreed || isLoading" (click)="payForStory(paymentObject.StoryId)">

scss class that a span element will recieve through [ngClass]:

&.error {
  border: 2px solid red;
}
like image 321
blixenkrone Avatar asked Oct 20 '25 21:10

blixenkrone


2 Answers

You cannot listen for click events on a disabled button. You could add a disabled class to the button and then listen for events as normal. Please review this stackblitz: https://stackblitz.com/edit/angular-3ksttt

Component:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  isButtonClicked: boolean = false;

  public disableButtonClick() {
    this.isButtonClicked = true;
  }
}

Template:

<button [ngClass]="isButtonClicked ? 'error' : ''" (click)="disableButtonClick()" class="disabled">BUTTON</button>
like image 198
Pete Avatar answered Oct 22 '25 12:10

Pete


Create a boolean property in your component, I.e. activeClass, listen for a click event on your button to toggle it, and then simply use ngClass to assign the class depending on the boolean.

[ngClass]="'yourClass': activeClass"

edit

As correctly pointed out, you can't listen to events on a disabled button. A solution to this is to wrap the element with a div and listen to events on that element (see this answer for more details) or to use a class to simulate the disabled effect.

like image 24
bugs Avatar answered Oct 22 '25 11:10

bugs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!