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?
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加