how to submit checked options on mat-checkbox
on focusot()
I try to solve this with @HostListener
and focusout()
but this is working wrong.
Anytime I check or uncheck the checkbox option focusout
is triggered.
I need to trigger focusout
only when I click anywhere outside (need to trigger this even if I click on a menu item or any other button), but if I click inside the checkboxes, needs to only push or remove from checkboxes array without trigger focusout
. Here is also stackblitz
export class CheckboxOverviewExample implements OnInit {
checkedOptions = [
{ title: 'aa', value: 1, checked: true },
{ title: 'bb', value: 2, checked: false },
{ title: 'cc', value: 3, checked: true },
{ title: 'dd', value: 4, checked: false },
];
selectedVal: any[] = [];
@HostBinding('attr.tabindex') tabIndex = '-1';
submitedVal: any[];
ngOnInit() {
const data = this.checkedOptions.filter((x) => x.checked);
this.selectedVal = data.map((x) => x.value);
}
@HostListener('focusout', ['$event'])
focusout(event) {
this.submit('this.selectedVal')
}
updateCheckboxArray(option, isChecked) {
if (isChecked) {
if (this.selectedVal.findIndex((x) => x === option.value) === -1) {
this.selectedVal.push(option.value);
} else {
const idx = this.selectedVal.findIndex((x) => x === option.value);
this.selectedVal.splice(idx, 1);
}
} else {
const idx = this.selectedVal.findIndex((x) => x === option.value);
this.selectedVal.splice(idx, 1);
}
}
}
I also try document:click
@HostListener('document:click', ['$event'])
clickOut(event) {
if (this.checkboxBox.nativeElement.contains(event.target)) {
this.submit('this.selectedVal')
}
}
but with this, if I click on any other button or menu item, this.submit()
is not triggered correctly