multiple multi example checkboxes json forms checkbox angular angular2-forms

json - example - multiple checkbox angular 4



Angular 2: Obtenga valores de mĂșltiples casillas marcadas (10)

  1. Acabo de simplificar un poco para aquellos que usan la lista de objetos Object. XYZ.Comonent.html

    <div class="form-group"> <label for="options">Options :</label> <div *ngFor="let option of xyzlist"> <label> <input type="checkbox" name="options" value="{{option.Id}}" (change)="onClicked(option, $event)"/> {{option.Id}}-- {{option.checked}} </label> </div> <button type="submit">Submit</button> </div>

    ** XYZ.Component.ts **.

  2. crear una lista - xyzlist.

  3. asignar valores, estoy pasando valores de Java en esta lista.
  4. Los valores son Int-Id, boolean -checked (puede pasar en Component.ts).
  5. Ahora para obtener valor en Componenet.ts.

    xyzlist;//Just created a list onClicked(option, event) { console.log("event " + this.xyzlist.length); console.log("event checked" + event.target.checked); console.log("event checked" + event.target.value); for (var i = 0; i < this.xyzlist.length; i++) { console.log("test --- " + this.xyzlist[i].Id; if (this.xyzlist[i].Id == event.target.value) { this.xyzlist[i].checked = event.target.checked; } console.log("after update of checkbox" + this.xyzlist[i].checked); }

Mi problema es realmente simple: tengo una lista de casillas de verificación como esta:

<div class="form-group"> <label for="options">Options :</label> <label *ngFor="#option of options" class="form-control"> <input type="checkbox" name="options" value="option" /> {{option}} </label> </div>

Y me gustaría enviar una matriz de las opciones seleccionadas, algo como: [option1, option5, option8] si las opciones 1, 5 y 8 están seleccionadas. Esta matriz es parte de un JSON que me gustaría enviar a través de una solicitud HTTP PUT.

¡Gracias por tu ayuda!


¡He encontrado una solución gracias a Gunter! Aquí está mi código completo si podría ayudar a alguien:

<div class="form-group"> <label for="options">Options :</label> <div *ngFor="#option of options; #i = index"> <label> <input type="checkbox" name="options" value="{{option}}" [checked]="options.indexOf(option) >= 0" (change)="updateCheckedOptions(option, $event)"/> {{option}} </label> </div> </div>

Aquí están los 3 objetos que estoy usando:

options = [''OptionA'', ''OptionB'', ''OptionC'']; optionsMap = { OptionA: false, OptionB: false, OptionC: false, }; optionsChecked = [];

Y hay 3 métodos útiles:

1) Para iniciar optionsMap :

initOptionsMap() { for (var x = 0; x<this.order.options.length; x++) { this.optionsMap[this.options[x]] = true; } }

2. para actualizar las optionsMap :

updateCheckedOptions(option, event) { this.optionsMap[option] = event.target.checked; }

3. para convertir optionsChecked en optionsChecked y almacenarlo en options antes de enviar la solicitud POST:

updateOptions() { for(var x in this.optionsMap) { if(this.optionsMap[x]) { this.optionsChecked.push(x); } } this.options = this.optionsChecked; this.optionsChecked = []; }


Acabo de enfrentar este problema y decidí hacer que todo funcione con la menor cantidad de variables posible, para mantener limpio el espacio de trabajo. Aquí hay un ejemplo de mi código

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

El método, que solicitó el cambio, es empujar el valor en el modelo o eliminarlo.

public changeModel(ev, list, val) { if (ev.target.checked) { list.push(val); } else { let i = list.indexOf(val); list.splice(i, 1); } }


Aquí hay una manera simple de usar ngModel (final Angular 2)

<!-- my.component.html --> <div class="form-group"> <label for="options">Options:</label> <div *ngFor="let option of options"> <label> <input type="checkbox" name="options" value="{{option.value}}" [(ngModel)]="option.checked"/> {{option.name}} </label> </div> </div>

// my.component.ts @Component({ moduleId:module.id, templateUrl:''my.component.html''}) export class MyComponent { options = [ {name:''OptionA'', value:''1'', checked:true}, {name:''OptionB'', value:''2'', checked:false}, {name:''OptionC'', value:''3'', checked:true} ] get selectedOptions() { // right now: [''1'',''3''] return this.options .filter(opt => opt.checked) .map(opt => opt.value) } }


Como pasé mucho tiempo resolviendo un problema similar, estoy respondiendo para compartir mi experiencia. Mi problema fue el mismo, para saber, obtener el valor de muchas casillas de verificación después de que se haya activado un evento específico. Probé muchas soluciones, pero para mí la más sexy es usar ViewChildren .

import { ViewChildren, QueryList } from ''@angular/core''; /** Get handle on cmp tags in the template */ @ViewChildren(''cmp'') components: QueryList<any>; ngAfterViewInit(){ // print array of CustomComponent objects console.log(this.components.toArray()); }

Encontrado aquí: https://.com/a/40165639/4775727

Posibles otras soluciones para la referencia, hay muchos temas similares, ninguno de ellos tiene como objetivo esta solución ...:


Espero que esto ayude a alguien que tiene el mismo problema.

templet.html

<form [formGroup] = "myForm" (ngSubmit) = "confirmFlights(myForm.value)"> <ng-template ngFor [ngForOf]="flightList" let-flight let-i="index" > <input type="checkbox" [value]="flight.id" formControlName="flightid" (change)="flightids[i]=[$event.target.checked,$event.target.getAttribute(''value'')]" > </ng-template> </form>

componente.ts

La matriz flightids tendrá otras matrices como esta [[verdadero, ''id_1''], [falso, ''id_2''], [verdadero, ''id_3''] ...] aquí verdadero significa que el usuario lo comprobó, falso significa que el usuario verificó y luego desmarcó . Los elementos que el usuario nunca ha verificado no se insertarán en la matriz.

flightids = []; confirmFlights(value){ //console.log(this.flightids); let confirmList = []; this.flightids.forEach(id => { if(id[0]) // here, true means that user checked the item confirmList.push(this.flightList.find(x => x.id === id[1])); }); //console.log(confirmList); }


La solución @ccwasden anterior funciona para mí con un pequeño cambio, cada casilla de verificación debe tener un nombre único; de lo contrario, el enlace no funcionará

<div class="form-group"> <label for="options">Options:</label> <div *ngFor="let option of options; let i = index"> <label> <input type="checkbox" name="options_{{i}}" value="{{option.value}}" [(ngModel)]="option.checked"/> {{option.name}} </label> </div> </div> // my.component.ts @Component({ moduleId:module.id, templateUrl:''my.component.html''}) export class MyComponent { options = [ {name:''OptionA'', value:''1'', checked:true}, {name:''OptionB'', value:''2'', checked:false}, {name:''OptionC'', value:''3'', checked:true} ] get selectedOptions() { // right now: [''1'',''3''] return this.options .filter(opt => opt.checked) .map(opt => opt.value) } }

y también haga que sur para importar FormsModule en su módulo principal

import { FormsModule } from ''@angular/forms''; imports: [ FormsModule ],


Me he encontrado con el mismo problema y ahora tengo una respuesta que me gusta más (puede ser usted también). He delimitado cada casilla de verificación a un índice de matriz.

Primero definí un objeto como este:

SelectionStatusOfMutants: any = {};

Entonces las casillas de verificación son así:

<input *ngFor="let Mutant of Mutants" type="checkbox" [(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />

Como sabe, los objetos en JS son matrices con índices arbitrarios. Por lo tanto, el resultado se está obteniendo tan simple:

Cuente los seleccionados así:

let count = 0; Object.keys(SelectionStatusOfMutants).forEach((item, index) => { if (SelectionStatusOfMutants[item]) count++; });

Y similar a esa búsqueda de los seleccionados como este:

let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => { return SelectionStatusOfMutants[item]; });

¡¿Lo ves?! Muy simple muy hermosa. TG.


crear una lista como: -

this.xyzlist = [ { id: 1, value: ''option1'' }, { id: 2, value: ''option2'' } ];

HTML: -

<div class="checkbox" *ngFor="let list of xyzlist"> <label> <input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label> </div>

entonces en su componente ts: -

onCheckboxChange(option, event) { if(event.target.checked) { this.checkedList.push(option.id); } else { for(var i=0 ; i < this.xyzlist.length; i++) { if(this.checkedList[i] == option.id) { this.checkedList.splice(i,1); } } } console.log(this.checkedList); }


<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" /> export class MyComponent { checked: boolean[] = []; updateChecked(option, event) { this.checked[option]=event; // or `event.target.value` not sure what this event looks like } }