1

I want to call a method that shows a warning toaster when i click on my disabled checkbox.

So here is my code:

<label>
  <input type="checkbox" checked="checked"
    [(ngModel)]="myCheckbox" 
    [disabled]="!hasCar"
    (change)="noCarToastr()"/>
</label>

TypeScript code:

noCarToastr(){
  let me  = this;
  if(!hasCar){
    me.toastr.warning("No Car Available");
  }
}
ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
Ibrahim Doqa
  • 59
  • 2
  • 13

3 Answers3

2

You can not trigger javascript events on a disabled element. Add the click listener over the label element.

<label (click)="noCarToastr()">
    <input type="checkbox" checked="checked"
        [(ngModel)]="myCheckbox" 
        [disabled]="!hasCar"
        (change)="noCarToastr(); $event.stopPropagation()"/>
        Car
</label>
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
1

Disabled elements won't fire mouse event, so instead of disabling just prevent the click action based on the hasCar property value which will prevent from checking the checkbox. For preventing the action use Event reference and Event#preventDefault method.

Template :

<label for="abc">test
    <input id="abc" type="checkbox" checked="checked"
        [(ngModel)]="myCheckbox" 
        (click)="noCarToastr($event, hasCar)"
        />
</label>

Component :

noCarToastr(event: Event) {
  let me = this;
  if (!this.hasCar) {
    event.preventDefault()
    me.toastr.warning("No Car Available");
  }
}

DEMO

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Rather than using @Output(change) use @Output(click), as change will only trigger when value of input is changed.

<label>
    <input type="checkbox" checked="checked"
        [(ngModel)]="myCheckbox" 
        [disabled]="!hasCar"
        (click)="noCarToastr()"/>
</label>

I would recommend using angular material as it provide other more intuitive option.

Hope this helps,