In my component I am trying to unselect all checkboxes with the same class name.
querySelector
selects only the first one each time (or once)... and querySelectorAll
does not select anything.
this is the function. I know its wrong to use jQuery like that but it illustrates my goal.
unsetAllOptions(){
var self = this;
var i = 0;
$("input.option_input").each(function(){
i++;
var element = self.elRef.nativeElement.querySelector("input.option_input")[i];
if(element.checked){
// console.log(i)
console.log('unchecking:',i);
element.checked=false;
element.dispatchEvent(new Event('change'));
element = "";
}
});
}
To achieve expected result, use below option
Option 1:
As you are using .each method, using index and value you can avoid querySelectorAll, reference - http://api.jquery.com/jquery.each/
code sample - https://codepen.io/nagasai/pen/aGoMKz?editors=1010
Option 2
Option2 and preferred way is to avoid document.querySelectorAll ,as it fetches all matching elements of the DOM irrespective of the current component
Steps to achieved expected result,
component.ts
component.html
code sample - https://stackblitz.com/edit/angular-aei58i?file=app/app.component.html
this worked for me but if you know a better way. Let me know