16

I want to get the values from my checkboxes but I can only get true or false.

Here is my template:

<h4>Categories</h4>
<div class="form-check" *ngFor="let cat of categories$|async">
    <input class="form-check-input" [(ngModel)]="cat.id" name="{{ cat.name }}" type="checkbox" id="{{cat.name}}">
    <label class="form-check-label" for="{{cat.name}}">
        {{cat.name}}
    </label>
</div>

Here is my component

this.categories$ = this.storeService.getAllCategories().pipe(
    map(result => (result as any).data),
    tap(r => console.log(r))
)

My component basically gets a list of the categories from an external api

enter image description here

4
  • 2
    You mean, when you check the checkbox with "Tom Ford", you should get "Tom Ford" as value, not true or false? Commented May 4, 2018 at 11:04
  • I want my data to be like so brand: Tom Ford or the id of the brand Commented May 4, 2018 at 11:10
  • try binding with name like this [(ngModel)]="cat.name" Commented May 4, 2018 at 11:15
  • Since checkbox takes Boolean value to be checked or un-checked. So you cant make checkbox to have "name" as value. You can make use of {change) method which triggers on check change, to do necessary stuffs. Commented May 4, 2018 at 11:17

6 Answers 6

25

You can simply use the change event to get an event when the checkbox clicked like below -

<div class="form-check" *ngFor="let cat of categories">
    <input class="form-check-input" (change)="onChange(cat.name, $event.target.checked)"name="{{ cat.name }}" type="checkbox" id="{{cat.name}}">
    <label class="form-check-label" for="{{cat.name}}">
        {{cat.name}}
    </label>
</div>

onChange(email:string, isChecked: boolean) {
      if(isChecked) {
        this.emailFormArray.push(email);
      } else {
        let index = this.emailFormArray.indexOf(email);
        this.emailFormArray.splice(index,1);
      }
  }

Update

In case of check all checkboxes you can loop over them -

    et checkBoxes = document.querySelectorAll('.form-check-input');
    checkBoxes.forEach(ele => ele.click())

working example

Sign up to request clarification or add additional context in comments.

6 Comments

Your example works but I am not seeing the checkboxes in my view?
Just the binding properly in your view and try to print the json in view part using |json pipe
how do I select all checkbox at once ?
@Santosh please check the updated answer and Stackblitz example
@PardeepJain, we should avoid use querySelectorAll in Angular (if it's unnecesary). Angular works relation model (variables in .ts) with view (the .html). So the "angular way" is use [(ngModel)] or Reactive Forms, see my answer
|
10

You can use change event with checkbox control like below,

<div class="form-check" *ngFor="let cat of categories$|async">
    <input class="form-check-input" [(ngModel)]="cat.id" name="{{ cat.name }}" type="checkbox" id="{{cat.name}}" (change)="onChangeCategory($event, cat)">
    <label class="form-check-label" for="{{cat.name}}">
        {{cat.name}}
    </label>
</div>

From component.ts file,

    tempArr: any = { "brands": [] };

    onChangeCategory(event, cat: any){ // Use appropriate model type instead of any
      this.tempArr.brands.push(cat.name);

    }

3 Comments

What I really want is an array of like: { "brands":[ "Tom Ford", "Rolex" ] }
Thanks this is just what I was looking for I am using indexOf to not add duplicates
what if I want all checkbox in false at begin?
4

it's unnecesary use event change and use auxiliar variable to store the array. You can simply use a getter to get the value

If we use as [(ngModel)] 'cat.isChecked'

<div class="form-check" *ngFor="let cat of categories">
    <input class="form-check-input" [(ngModel)]="cat.isChecked" name="{{ cat.name }}" type="checkbox" id="{{cat.name}}">
    <label class="form-check-label" for="{{cat.name}}">
        {{cat.name}}
    </label>
</div>

We can has some like:

get values()
{
    return this.categories.filter(x=>x.isChecked).map(x=>x.id)
}

If we need a "check all" we can use

<input #checkAll type="checkbox" (change)="selectAll(checkAll.checked)">

  selectAll(checked:any)
  {
    this.categories.forEach(x=>x.isChecked=checked)
  }

See the stackblitz

1 Comment

Good approach you are using in the answer.
0

You want to get values from checkboxes. Checkbox represents a boolean. So getting true and false is what you should get.

Comments

0

Check this Angular Typescript example link

enter image description here

Update HTML template

  <ul class="checkbox-items">
    <li *ngFor="let item of checkboxesDataList">
      <input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
    </li>
  </ul>

Component Class

  checkboxesDataList = [
    {
      id: 'C001',
      label: 'Photography',
      isChecked: true
    },
    {
      id: 'C002',
      label: 'Writing',
      isChecked: true
    },
    {
      id: 'C003',
      label: 'Painting',
      isChecked: true
    },
    {
      id: 'C004',
      label: 'Knitting',
      isChecked: false
    },
    {
      id: 'C004',
      label: 'Dancing',
      isChecked: false
    },
    {
      id: 'C005',
      label: 'Gardening',
      isChecked: true
    },
    {
      id: 'C006',
      label: 'Drawing',
      isChecked: true
    },
    {
      id: 'C007',
      label: 'Gyming',
      isChecked: false
    },
    {
      id: 'C008',
      label: 'Cooking',
      isChecked: true
    },
    {
      id: 'C009',
      label: 'Scrapbooking',
      isChecked: false
    },
    {
      id: 'C010',
      label: 'Origami',
      isChecked: false
    }
  ]


  // Selected item
  fetchSelectedItems() {
    this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
      return value.isChecked
    });
  }

  // IDs of selected item
  fetchCheckedIDs() {
    this.checkedIDs = []
    this.checkboxesDataList.forEach((value, index) => {
      if (value.isChecked) {
        this.checkedIDs.push(value.id);
      }
    });
  }

Comments

0
Angular version 13

here is my code in .ts file
Declare th Array
  languages_array: Array<any> = [
{
  marathi_array: [
    {
      id: "marathi_speak", name: "marathi_speak", selected: false
    },
    {
      id: "marathi_write", name: "marathi_write", selected: false
    },
    {
      id: "marathi_read", name: "marathi_read", selected: false
    },
  ]
},
{
  hindi_array: [
    {
      id: "hindi_speak", name: "hindi_speak", selected: false
    },
    {
      id: "hindi_write", name: "hindi_write", selected: false
    },
    {
      id: "hindi_read", name: "hindi_read", selected: false
    },
  ]
},
{
  english_array: [
    {
      id: "english_speak", name: "english_speak", selected: false
    },
    {
      id: "english_write", name: "english_write", selected: false
    },
    {
      id: "english_read", name: "english_read", selected: false
    }
  ]
}

];

and i check the change event

  CheckBox(e: any, items: any) {
items.selected = e.target.checked
console.log(this.languages_array);

}

and in my .html file contain

<div class="col-md-12">
                <div class="table-responsive">
                  <table class="table table-hover table-bordered table-striped">
                    <thead>
                      <tr>
                        <th scope="col">Language</th>
                        <th scope="col">Speak</th>
                        <th scope="col">Write</th>
                        <th scope="col">Read</th>
                      </tr>
                    </thead>
                    <tbody class="text-center">
                      <tr>
                        <th> Marathi</th>
                        <td *ngFor="let item1 of languages_array[0].marathi_array; let i=index">
                          <input type="checkbox" (change)="CheckBox($event,item1)" [checked]="item1.selected">
                        </td>
                      </tr>
                      <tr>
                        <th> Hindi</th>
                        <td *ngFor="let item2 of languages_array[1].hindi_array; let i=index">
                          <input type="checkbox" (change)="CheckBox($event,item2)" [checked]="item2.selected">
                        </td>
                      </tr>
                      <tr>
                        <th> English</th>
                        <td *ngFor="let item3 of languages_array[2].english_array; let i=index">
                          <input type="checkbox" (change)="CheckBox($event,item3)" [checked]="item3.selected">
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
and when you submit the form you can check this languages_array values using 

submit()
{
console.log(this.languages_array)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.