Angular 2 + how to select and loop over multiple elements with the same selector (elementRef.nativeElement)

∥☆過路亽.° 提交于 2019-12-08 01:31:52

问题


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 = "";
        }
    });
}

回答1:


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/

$("input.option_input").each(function(index,element){
        if(element.checked){
            element.checked=false;
            element.dispatchEvent(new Event('change'));
            element = "";
        }
    });

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,

  1. Use Renderer and ElementRef to fetch current component elements
  2. Use this.elem.nativeElement.querySelectorAll for fetching matching elements

component.ts

import { Component, Renderer, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  constructor(private renderer: Renderer, private elem: ElementRef){}

  unsetAllOptions(){
    let elements = this.elem.nativeElement.querySelectorAll('.option_input');
    elements.forEach(element => {
     if(element.checked){
        element.checked = false
     }
});
 }
}

component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<input type="checkbox" class="option_input" checked>
<input type="checkbox" class="option_input" checked>
<input type="checkbox" class="option_input" checked>
<input type="checkbox" class="option_input" checked>
<input type="checkbox" class="option_input">

<button (click)="unsetAllOptions()">UncheckAll</button>

code sample - https://stackblitz.com/edit/angular-aei58i?file=app/app.component.html




回答2:


this worked for me but if you know a better way. Let me know

unsetAllOptions(){
    var self = this;
    var i = -1;
    $("input.option_input").each(function(){
        i++;
        var element = self.elRef.nativeElement.querySelectorAll("input.option_input")[i];
        element.checked=false;
    });
}


来源:https://stackoverflow.com/questions/49886571/angular-2-how-to-select-and-loop-over-multiple-elements-with-the-same-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!