简体   繁体   中英

How to get dynamically created checkbox list selected values in Angular?

Here is my dynamically created checkboxes list

<span *ngFor="let name of _category">
<span class="TextMaroonBold"> {{name.AliasName}}</span>
<div class="ex1">
<span *ngFor="let option of name.arrOptions" class="checkbox">

        <div class="form-check" style="padding-left: 35px;">
            <input class="form-check-input" type="checkbox" (change)="changed(evt)" name="exampleRadios" id={{name.DisplayOrder}} value="{{option.options}}">
            <label class="form-check-label" for="exampleRadios1">
                {{option.options}}
            </label>
        </div>

</span>

This is how my checkbox list looks:-

在此处输入图像描述

Now what i want is to get the checkboxlist name/ID and its selected values. Eg If I have selected some values in "certification" check box I should get the name of the checkboxlist ie Certification and its selected values.

Rohit, the question is "what about your data?". It's looks like you has some like

_category=[
   {
     name:"Certification"
     arrOptions:[{options:"Current"},{options:"Process"}..]
   }, 
   {
     name:"Heigth"
     arrOptions:[{options:"50-80 cm"},{options:"81-120 cm"}..]
   },
   ... 
]

You can simply use in our inputs [(ngModel)]

<input class="form-check-input" type="checkbox" [(ngModel)]="option.checked"
 name="exampleRadios" id={{name.DisplayOrder}} >    

This add a new property to your elements options called checked that make it true/false, just add in your.html to see it

<pre>
{{_category|json}}
</pre>

Well, you can get an array of Certification, Heigth and Width selected, so you can do

const certifications=_category[0].arrOptions.filter(o=>o.checked).map(o=>o.options)
const heigths=_category[1].arrOptions.filter(o=>o.checked).map(o=>o.options)
const widths=_category[2].arrOptions.filter(o=>o.checked).map(o=>o.options)

I have simulated the scenario on this stackblitz playground - link

It will dynamically show you the changes you make on checkbox in pre tag at the bottom. Hope it helps. --Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM