I'm trying to get the values of checked checkboxes and put them into a strig , that string will be used in my api. I want to get the values once the checkbox is checked and retrieve the value if that checkbox is unchecked.
<div *ngFor="let x of groupesTable">
<input type="checkbox" [(ngModel)]="group" (change)="">
{{x.nom_groupe | uppercase}}
</div>
I've no idea how to do that or what method should I use in typescript. Any help would be appreciated.
This is an update
<div class="form-check" *ngFor="let x of groupesTable">
<label class="form-check-label" for="check1">
<input type="checkbox" class="form-check-input" nom="check1" [value]= "x.nom_groupe"
name="x.nom_groupe" (change)="callMe($event, x.nom_groupe)" [(ngModel)]="grp">{{x.nom_groupe | uppercase}}
</label>
</div>
and in the .ts file i did this
callMe(event, nom) {
if (event.target.checked)
{
console.log(nom);
this.nomgrps=this.nomgrps+nom.toUpperCase()+" ";
console.log(this.nomgrps);
}
else {
console.log(this.nomgrps);
}}
But this also doesn't work , i don't know why it checks all the checkboxes while i only check one.
It checks and unchecks all the boxes together because all your formControls are bound to the same variable: grp
. Either create an array of new form models which you can use to get the checkboxes which are checked or you use the object in the loop by adding a new property checked
on it on the fly.
Something like:
<div *ngFor="let x of groupesTable">
<input type="checkbox" [(ngModel)]="x.checked" (change)="foo()">
{{x.nom_groupe | uppercase}}
</div>
foo() {
let checkedStrings = this.groupesTable.reduce((acc, eachGroup) => {
if (eachGroup.checked) {
acc.push(eachGroup.nom_groupe.toUpperCase())
}
return acc
}, []).join(" ")
console.log(checkedStrings);
}
https://stackblitz.com/edit/angular-dj95pg?file=src%2Fapp%2Fapp.component.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With