Checkbox's event has no way to get the checked value of the source checkbox if we would like to use the (click) event.
Define event.checked or a similar property.
The values are undefined
https://stackblitz.com/edit/matcheckbox-checked
I would like to make a checkbox, where value only gets changed if the underlying HTTP request succeeds (there is a confirm box after the click and the request returns the entity changed, so I can get the updated value and change the values based on that, also I display notification about the success or failure..etc). The checkbox should not change value before I handle the event.
I used "@angular/core": "^6.1.2", "@angular/material": "^6.4.6" and "typescript": "^2.9.2", chrome, but you can check the stackblitz too.
https://github.com/angular/material2/issues/1142
https://stackoverflow.com/questions/52364296/matcheckbox-preventdefault-and-event-checked-value
As Chellappan pointed out in my SO question, this (stackblitz) works, but it would be easier to just get it from the event and the (change) event still can't stop the event propagation.
HTML:
<mat-checkbox #ref
[checked]="checked"
(click)="onClick($event)"
>onClick me!</mat-checkbox>
TS:
@ViewChild('ref') ref;
onClick(event) {
event.preventDefault();
console.log('onClick this.ref._checked '+ this.ref._checked);
this.ref._checked = !this.ref._checked;
}
The click event on the checkbox is just the native click event, which doesn't know anything about the checkbox itself. Using the change event or just getting a handle on the MatCheckbox instance directly (e.g. with @ViewChildren) would be the recommended approach.
You can do this:
<div *ngFor="let item of items">
<mat-checkbox #checkbox="matCheckbox" [checked]="item.selected"
(click)="somethingClick(checkbox, item)">{{ item.label }}</mat-checkbox>
</div>
When you have #checkbox="matCheckbox" it sets the checkbox variable to be an instance of matCheckbox directive. So we just pass this directly to the handler which becomes:
somethingClick(checkbox: MatCheckbox, item: { id: string } ) { ... }
You can pass any extra parameters you want (here I'm passing the list item).
Also in a case like this I like to set the type of 'item' to be a property bag of the data I will actually be using. This makes the whole thing more reusable.
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
_This action has been performed automatically by a bot._