Angular 2 + 如何 select 并使用相同的 select 或 (elementRef.nativeElement) 遍历多个元素

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

在我的组件中,我试图取消select 所有具有相同 class 名称的复选框。

querySelector select 每次(或一次)只有第一个...并且 querySelectorAll 没有 select 任何东西。

这是函数。我知道这样使用 jQuery 是错误的,但它说明了我的目标。

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

这对我有用,但如果您知道更好的方法。让我知道

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

要达到预期结果,请使用以下选项

选项 1:

当你使用.each 方法时,使用索引和值你可以避免 querySelectorAll,参考 - 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 = "";
        }
    });

代码示例 - https://codepen.io/nagasai/pen/aGoMKz?editors=1010

选项 2

Option2 和首选方法是避免 document.querySelectorAll ,因为它会获取 DOM 的所有匹配元素,而不管当前组件

实现预期结果的步骤,

  1. 使用 Renderer 和 ElementRef 获取当前组件元素
  2. 使用this.elem.nativeElement.querySelectorAll获取匹配元素

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(){
    const 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>

代码示例 - https://stackblitz.com/edit/angular-aei58i?file=app/app.component.html