George hatouts George hatouts - 3 years ago 262
Javascript Question

How to get the selected checkboxes IDS in angular 4

I have generated 600 checkboxes



And I want to get all the checked checkboxes IDs, There is any way that I can get the selected checkboxes ids like this format

["id_1", "id_2", "id_3", "id_4",]

This is the data



FinalCategories : any = [

{id:"id_1",name:"category name"},
{id:"id_1",name:"category name"},
{id:"id_1",name:"category name"},
{id:"id_1",name:"category name"},
{id:"id_1",name:"category name"},
{id:"id_1",name:"category name"}
600 ++

]


Angular 4 HTML component



<div *ngFor="let item of Items" >
<md-checkbox id="{{item.id}}" [checked]="item['checked']" value="{{item.name}}"
(change)="getSelectedCategories()" name="categories_group">
{{ item.name }}
</md-checkbox>
</div>



Ok now how to get the checked checkbox IDs OR DOM Elements


In this Format




I want the output to be array [ "id_1", "id_33", "id_750" ]

Answer Source

Your code is really confusing. But I will try.

add in ngInit()

this.FinalCategories.map((element)=>element.checked = false)

and in your html.

<div *ngFor="let finalCategory of FinalCategories | filterArray:subCategory" >
  <md-checkbox [(ngModel)]="finalCategory.checked">
    {{ finalCategory.name}}
  </md-checkbox>
</div>

And then you function will do:

yourFunction(){
   let yourList = [];
   this.FinalCategories.map((item)=>{if(item.checked){yourList.push(item.id)}})
   return yourList
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download