Apologies if this EXACT question has been asked elsewhere as I've searched over the internet but I've found somewhat similar scenarios and their solutions but not one that I'm in search of. Hoping someone could assist me in this. So here goes,
I need to obtain the value of all the checkboxes that have been
checked. The checkboxes are dynamically created based on the number of Array (assets) items
I am creating a form which uses ngFor to go through an array, and create checkboxes for each field. So what I've done is something like this,
<form>
<div class="row"><label>Assets</label></div>
<div *ngFor='let asset of assets' [(ngModel)]='assets'>
<div class="col-8"><input type="checkbox" name="{{asset}}" (change)="onChange()"></div>
<div class="col-35"><label>{{asset}}</label></div>
</div>
</form>
There are plenty of solutions outside but unfortunately everyone is coming with an example where the array is more like a Key:Value pair, for instance,
this.someArray = [
{id:1, name: someName, isSelect: false},
{id:2, name: someOtherName, isSelect: false}
]
I understand how to work with such kind of array structure but in my case, I have the following String Array,
assets: String[] = ['one', 'two', 'three'];
My question is, how can I get all the values that have been checked when I have just a simple Array of Strings. What I've done uptil now is something like this,
asset.component.html
<form>
<div class="row"><label>Assets</label></div>
<div *ngFor='let asset of assets' [(ngModel)]='assets'>
<div class="col-8"><input type="checkbox" name="{{asset}}" (change)="onChange()"></div>
<div class="col-35"><label>{{asset}}</label></div>
</div>
</form>
asset.component.ts
export class AppComponent {
name = 'Angular ' + VERSION.major;
assets: String[] = ['one', 'two', 'three'];
onChange(): void {
alert(this.assets);
}
}
Any help will be greatly appreciated. Looking forward to hearing from you soon,
For references, here is the StackBlitz implementation (Not completed yet) though,
https://stackblitz.com/edit/angular-ivy-jtnzhp?file=src/app/app.component.html
Kind Regards
Copyright Notice:Content Author:「rac3b3nn0n」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71522120/get-values-of-all-selected-checkboxes-using-angular