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;
}
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With