Por favor, dê uma olhada no código abaixo.
import { Component,ViewChild,QueryList,ViewChildren } from "@angular/core"
@Component ({
selector : "other-component",
template : `
<h2>OtherComponent<h2>
<table #tab id="tab">
<tr *ngFor="let val of valArray">
<td>{{val}}</td>
<input type="checkbox" [value]="val">
</tr>
</table>
<button (click)="getChecked()">click me</button>`
})
export class OtherComponent{
valArray = ["one","two","three","four"];
@ViewChild ("tab") elem;
getChecked = () => {
console.log (this.elem.nativeElement.children[0].children)
}
}
No final da linha da tabela há caixa de seleção que foi atribuído o valor da linha (objeto JSON) agora eu quero coletar todas as caixas marcadas em angular 2.
Em javascript simples eu posso fazer isso facilmente como abaixo
var yy = document.getElementById("tab").getElementsByTagName("input");
Eu tenho o que eu estava procurando por this.elem.nativeElement.children[0].children
isso me deu variedade de tr elementos dos quais eu chequei caixas de entrada
Existe alguma maneira melhor de fazer isso em angular 2?
Respostas:
8 para resposta № 1Alterar html (adicionar #cbx
para input
) gostar:
<tr *ngFor="let val of valArray"><input #cbx type="checkbox" [value]="val"></tr>
Em seguida, na sua classe de componentes:
@ViewChildren("cbx") checkboxes;
getChecked = () => {
console.log(this.checkboxes.toArray().map(x => x.nativeElement));
}
Ele imprimirá a matriz de caixas de seleção desejadas
Veja também ao vivo Exemplo de Plunker
Atualizar
O caminho alternativo está usando dom api diretamente:
@ViewChild ("tab") elem;
getChecked = () => {
console.log(this.elem.nativeElement.getElementsByTagName("input"));
console.log(this.elem.nativeElement.querySelectorAll("input"));
}