Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular component: disable click event

I am creating a reusable component like this one:

<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>

I would like to disabled the click event when the property isDisabled is true, I tried something like that but it doesn't work.

packages/component/my-button.component.html

<button  [disabled]="isDisabled" #myButton>
        <ng-content></ng-content>
</button>

packages/component/my-button.component.ts

@ViewChild('uxButton') uxButton: ElementRef;
@Input() isDisabled: boolean = false;

this.myButton.nativeElement.parentNode.removeEventListener('click' , (e) => {
       e.stopPropagation();
});
like image 970
Gelso77 Avatar asked Mar 28 '19 16:03

Gelso77


3 Answers

try like this

<button  [disabled]="isDisabled" (click)="btnClick.emit($event)">
        <ng-content></ng-content>
</button>

@Input() isDisabled: boolean = false;
@Output() btnClick = new EventEmitter();

Use Output and By default the button click event won't work if button is disabled. take advantage of it

<my-button [isDisabled]="isDisabled" (btnClick)="click($event)"> submit </my-button>
like image 101
Sheik Althaf Avatar answered Oct 18 '22 20:10

Sheik Althaf


It is also solved by the following CSS:

# This prevents host to get a direct click
:host {
  pointer-events: none;
}

# This prevents the span inside the button to "steal" the click from the button
:host /deep/ button span {
  pointer-events: none;
}

# Now only the button can get a click 
# Button is the only smart enough to stop propagation when needed
button {
  pointer-events: auto;
}

And now you don't to pass down the click event manually like in other answers: You have the old (click) event back :D

<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>

In your custom component, you just need to pass down the disabled property:

<button  [disabled]="isDisabled" #myButton>
        <ng-content></ng-content>
</button>

Also consider the stackblitz modified from another stackoverflow answer.

like image 13
ErikWitkowski Avatar answered Oct 18 '22 20:10

ErikWitkowski


You can check it on (click) attribute:

<my-button [isDisabled]="isDisabled" (click)="!isDisabled && click($event)"> submit </my-button>
like image 5
dm777 Avatar answered Oct 18 '22 20:10

dm777