How to Get Checkbox Value in Angular

how to get checkbox value in angular?

you need to use change event

<mat-checkbox (change)="checkCheckBoxvalue($event)">Check me!</mat-checkbox>

checkCheckBoxvalue(event){
console.log(event.checked)
}

Working Example

other ways -

  • You can use two way data binding for the same like mentioned below -

    <input type="checkbox" name="myData" [(ngModel)]="isChecked">
  • You can use a local variable as well and fetch the value in controller side like below -

    <input type="checkbox" name="myData" #myCheckbox>

    @ViewChild('myCheckbox') myCheckbox;
    console.log(myCheckbox, 'Value of checkbox');
  • Other way is you can use formControl for the same, either it can be model-driven form or template-driven form.

Getting value of checkbox using angular

You can use (change) which fires every time when change detects on the input element and then write a custom logic to get the checked items from list, for example:

HTML:

<div class="list-group-item" *ngFor="let ticket of tickets">
<input type="checkbox" [name]="ticket.id" [id]="ticket.id" [value]="ticket.id" (change)="onCheck(ticket.id)"/>
<label for="{{ ticket.id }}">{{ ticket.name }}</label>
</div>

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

TS Code:

import { Component } from "@angular/core";

@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
tickets = [{ id: 1, name: "Test1" }, { id: 2, name: "Test2" }];

checkedTickets = [];

onCheck(evt) {
if (!this.checkedTickets.includes(evt)) {
this.checkedTickets.push(evt);
} else {
var index = this.checkedTickets.indexOf(evt);
if (index > -1) {
this.checkedTickets.splice(index, 1);
}
}
console.log(this.checkedTickets);
}
}

Working Demo

Get checkbox name, value and checked state in Angular

You may replace your ngModelChange event to click event where you pass the event object as

(change)="GetStats($event)"

and in the component method, try to get name, value and checked state as

GetStats(event: Event) {
console.log(event.target.name, event.target.value, event.target.checked);
}

See more in the stackblitz https://stackblitz.com/edit/angular-get-dynamic-checkbox-attributes

How to get checkbox value in angular 5 app

If you're using Angular 2> you should use the checked attribute for using one way binding, that the UI will only read the value of check. Using this method you would have to update the check value in your component.

 <input 
type="checkbox"
name="questionAnswerState"
[checked]="check"
(change)="isAnswerProvided($event, check)"
/> Answer Provided?

or if you're after two way binding, where the state is controlled completely by the UI you can use ngModel like this:

 <input 
type="checkbox"
name="questionAnswerState"
[(ngModel)]="check"
(change)="isAnswerProvided($event, check)"
/> Answer Provided?

How to get the value from angular material checkbox

The click event on the checkbox is just the native click event, which
doesn't know anything about the checkbox itself. Using the change
event or just getting a handle on the MatCheckbox instance directly
(e.g. with @ViewChildren) would be the recommended approach.

(c) https://github.com/angular/material2/issues/13156#issuecomment-427193381

<section *ngFor="let item of list">
<mat-checkbox [checked]="item.value" (change)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

Angular 2 Checkbox value

use ngModel directive and bind it to player.selected

html:

<td>
<input
type="checkbox"
class="form-check-input"
[id]="bullsPlayers[i]"
[name]="bullsPlayers[i]"
[(ngModel)]="player.selected"
value="player.fullName"
(change)="updateBullsPlayer()"/>
</td>

component.ts:

updateBullsPlayer() {
this.selectedBullsPlayers = selectedBullsPlayers.filter((item) => item.selected)
}

don't worry about selected field it will added automatically by ngModel

get multiple checkbox value as an array in angular

Thre're several errors in your code.

The last stackblitz you indicate (that gone from this SO) is an "imaginative" way to mannage a series of check-boxes to feed a formControl that store an array of strings. The idea is that the input has [checked] and (change), but NOT formControlName (it's the reason because at first the check-boxes became "checked"). The formControl has no input in the form. Yes, the formControl exist, but has no input.

The [checked] of the check-box is a function that indicate if the "option" is include in the value of the control (using indexOf)

The (change) has as arguments, the indexes -to localize the formControl-, the value of the "option" and if is checked or not.

A more simple stackblitz to show this concept:

<!--see that "answer" has no input, it's only a variable in .ts-->
<div *ngFor="let option of options">
<input #check type="checkbox"
[checked]="answer.indexOf(option)>=0"
(change)="onChange(option,check.checked)"
>
{{option}}
</div>

answer=["check 2"]
options=["check 1","check 2","check3"]
onChange(option:string,checked:boolean)
{
if (checked && this.answer.indexOf(option)<0)
this.answer=[...this.answer,option]
.sort((a,b)=>this.options.indexOf(a)>this.options.indexOf(b)?1:-1)
if (!checked)
this.answer=this.answer.filter(x=>x!=option)
}

Well, in your code

1.-Change the form (please, see the comments in the code)

    <div *ngIf="form.type == 'checkbox'">
<p>{{form.title}}</p>
<div *ngFor="let option of form.options">
<!--in your code WRONG (change)="onChange(i,j, form.code,check.checked)" -->
<!-- see that we need send the "option", not the form.code-->
<label><input #check (change)="onChange(i,j, option,check.checked)"
<!--use checked, not value, and remove the "toString"-->
[checked]="answers[i].value.forms[j].answer.indexOf(option)>=0"
<!--see that we has no formControlName="answer" -->
type="checkbox">{{option}}</label>
</div>
</div>

The function onChange, it's simply if checked=true add the "code" and if checked=false remove the "code". Well, there are a dificult that is "sort" the responses. For sort the response, we compare the indexOf the value in the "options"

I use an auxiliar variable "options" to get the "options"

2.-Change your function onChange by

  onChange(indexi: number, indexj: number, code: string, isChecked: boolean) {
const control = this.answerArray.at(indexi).get("forms")["controls"][indexj]
.controls.answer;

const options=this.listFormField[indexi].sectionItems[indexj].options
//options will be, eg. ["check 1","check 2","check 3"]
if (isChecked && control.value.indexOf(code) < 0)
control.setValue(
[...control.value, code].sort((a: string, b: string) =>
options.indexOf(a) >options.indexOf(b)
? 1
: -1
)
);

if (!isChecked && control.value.indexOf(code) >= 0)
control.setValue(control.value.filter(x => x != code));
}

NOTE: You need revised the code, Actually, when you create the form, all yours "answers" are arrays (only need to be array the "answer" that they are ansers of a check-boxs)

Updated To avoid errors if answer is null, we can or avoid when create the form or, another option, change the code in checked as

[checked]="(answers[i].value.forms[j].answer || []).indexOf(option)>=0"

To path value we can, if only is an element, e.g.

const i=0
const j=1
this.response.get('answers.'+i+'.forms.'+j+'.answer')
.patchValue(["check 1","check 2"])

Yes, to get an "answer" we can use "get" using the index. Perhafs this makes understand because when we use a formArray of formGroup, we write [formGroupName]="i". If we want to make a pathValue over a FormGroup, we need take account, that if we make pathValue over an array, pathValue NOT add elements to the formArray, so if we send more elements, this it's not added. futhermore, if we send less elements, pathValue, remove the elements

take account this, we can also make,e.g.

this.response.get('answers.'+i+'.forms')
.patchValue(
[
{answer:"radio 2"},
{answer:["check 1","check 2"]},
{answer:"text input"},
{answer:"text area"},
{answer:["check 6"]},
]
)


Related Topics



Leave a reply



Submit