Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person

Categories

I want to prevent a checkbox from becoming selected if a handler bound to the click event encounters an error. Here's a section of my component's HTML

<input class="form-check-input" type="checkbox" 
  id="category-{{cat.id}}" value="{{cat.id}}"
  (click)="toggleCategory(cat)"
  [checked]="menuItem.hasCategory(cat.id)"
>

https://github.com/angular/angular/issues/2042 indicates that returning false from the toggleCategory method should work, and indeed it does: clicking on the checkbox does not cause the checkbox to appear checked when toggleCategory looks like this:

toggleCategory(category:Category):boolean {
  return false;
}

However, the actual implementation of toggleCategory invokes an HttpClient POST, and so it's not known until later whether an error occurred.

I tried making toggleCategory return Observable<boolean> but that doesn't work.

toggleCategory(category:Category):Observable<boolean> {      
  return of(false);
}

I've seen Angular 2 Checkbox preventDefault in which the accepted answer seems to suggest wrapping the <input> element in an <a> and handling the click event there. This behaves the same way as clicking on the checkbox does for me.

Any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
408 views
Welcome To Ask or Share your Answers For Others

1 Answer

I suggest to put the MouseEvent itself additionally to the toggleCategory as parameter:

<input type="checkbox" (click)="toggleCategory($event, cat)">

And in toggleCategory the $event.target will be the input itself, and its checked porterty can be changed to the wished value. So if we want to prevent the checkbox to be checked, following code snippet can be used:

toggleCategory($event: MouseEvent, category: Category) {
   ($event.target as HTMLInputElement).checked = false;
}

The above example sets the checkbox always back. This code snippet can be in the error cases to prevent the checkbox selection.

Here is a stackblitz example, if you want to play around with it: https://stackblitz.com/edit/angular-op51jp?file=src/app/app.component.ts


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...