How to Pass the Checked and Unchecked Value of Checkboxes in Component.Ts File in Angular

How to pass the checked and unchecked value of checkboxes in component.ts file in angular?

app.component.ts

import { Component } from '@angular/core'

@Component({
selector: 'my-app',
templateUrl: 'src/app.component.html'
})
export class AppComponent {
documents = [
{
docId:1,
docName:'Proforma Invoice',
checked: true
},
{
docId:2,
docName:'Packing List',
checked: false
}
];

checkboxClicked() {
this.documents.filter(x => x.checked).map(x => {
console.log(x.docId);
})
}

}

Note: You should not pass id as checkbox value. Create some boolean property with the object.

app.component.html

<ng-container *ngFor="let document of documents">
<input type="checkbox" name="checkbox{{document.docId}}" [(ngModel)]="document.checked" (change)="checkboxClicked()" />
</ng-container>

Angular - Check/Uncheck All Checkboxes

Updating my answer as per our discussion in comments, to check/uncheck all checkboxes.

component.ts

checklist

checkUncheckAll(evt) {
this.checklist.forEach((c) => c.isSelected = evt.target.checked)
}

ngOnInit() {
this.checklist = [
{id:1,value:'Elenor Anderson',isSelected:false},
{id:2,value:'Caden Kunze',isSelected:false},
{id:3,value:'Ms. Hortense Zulauf',isSelected:false},
{id:4,value:'Grady Reichert',isSelected:false},
{id:5,value:'Dejon Olson',isSelected:false},
{id:6,value:'Jamir Pfannerstill',isSelected:false},
{id:7,value:'Aracely Renner DVM',isSelected:false},
{id:8,value:'Genoveva Luettgen',isSelected:false}
];
}

In your template

<div class="container">
<div class="text-center mt-5">
<div class="row">
<div class="col-md-6">
<ul class="list-group">
<li class="list-group-item">
<input type="checkbox" name="list_name" value="m1" (change)="checkUncheckAll($event)"/> <strong>Select/ Unselect All</strong>
</li>
</ul>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of checklist">
<input type="checkbox" [checked]="item.isSelected" name="list_name" value="{{item.id}}"/>
{{item.value}}
</li>
</ul>
</div>
</div>
</div>
</div>

Working DEMO

Passing parameters on checking and un-checking of a checkbox

The ngModel value is set to a single variable isChecked. This variable is passed to all checkboxes. All the checkboxes will reflect their state based on isChecked. You could use some thing like student.checked. You could set the value in the onChange fucntion.

onChange(isChecked, student) {
student.isChecked = isChecked;
}
<ul>
<li [(ngModel)]="student" *ngFor="let student of studentsToLOad" [value]="student">
<b>{{student.name}}</b>
<input type="checkbox" id="present" name="present" [(ngModel)]="student.isChecked" (change)="onChange(isChecked, student)" />
</li>
</ul>

Angular 4 checkbox change value

This it what you are looking for:

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />

Inside your class:

checkValue(event: any){
console.log(event);
}

Also include FormsModule in app.module.ts to make ngModel work !

Hope it Helps!

Angular checkbox hard-coded to [checked]="true" isn't always true

Pass an $event in onChange function <input type="checkbox" (change)="onChange($event)" [checked]="isChecked()"> Click me and I\'ll uncheck (but I shouldn\'t) so that you can change the value of input.

onChange(e) {
console.log("changed.")
//here u are again setting the input value as true.
e.target.checked = true;
}

Another way of doing, add (click) event in your template like this
(click)="onClick($event)"

and Define a onClick(e) function in your component,

onClick(e){
//here u are again setting the input value as true.
e.target.checked = true;
}

But (click) event is better than (change) for this situation.

Toggle Angular checkbox with string values instead of boolean true/false

This solution is based on the solution link by Eliseo.

The checkbox toggles values as "optin" or "optout" when checked/unchecked and is initialized as "optin" by default in .ts file

component.html file

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">

<div class="form-group">

<div class="optClass">
<input type="checkbox"
[ngModel]="optOutForm.get('optOutFlag1')?.value==='optin'"
(ngModelChange)="optOutForm.get('optOutFlag1').setValue($event?'optin':'optout')"
[ngModelOptions]="{standalone:true}" id="privacy">

<label "for="privacy" id="check1">Checkbox 1</label>
</div>

<div class="optClass">
<input type="checkbox"
[ngModel]="optOutForm.get('optOutFlag2')?.value==='optin'"
(ngModelChange)="optOutForm.get('optOutFlag2').setValue($event?'optin':'optout')"
[ngModelOptions]="{standalone:true}" id="security">

<label "for="security" id="check1">Checkbox 2</label>
</div>

<div class="optClass">
<input type="checkbox"
[ngModel]="optOutForm.get('optOutFlag3')?.value==='optin'"
(ngModelChange)="optOutForm.get('optOutFlag3').setValue($event?'optin':'optout')"
[ngModelOptions]="{standalone:true}" id="consent">

<label "for="consent" id="check1">Checkbox 3</label>
</div>
</div>
</form>

component.ts file

optOutForm:FormGroup

constructor(private fb:FormBuilder){}

ngOnInit(){
this.optOutForm=this.fb.group({
optOutFlag1:['optin',Validators.required],
optOutFlag2:['optin',Validators.required],
optOutFlag3:['optin',Validators.required]
});
}

Angular - How can I check a checkbox based on values in Array?

If you are using a model then this will be very easy and clean.

Say your calibres are of below model

  calibres = [
{value: 1, isSelected: false},
{value: 5, isSelected: false},
{value: 4, isSelected: false}
];

When you get an array from backend just check like

backendArray = [2,4];

And a function to check isSelected flags after you fetch data

this.calibres = this.calibres.map(
(elem) =>{ elem.isSelected = this.backendArray.indexOf(elem.value) != -1 ? true : false;
return elem});

HTML section use checked attribute. Pass calibre when on change and do your toggle logic to isSelected flag

<div >
<mat-checkbox #checkBox
*ngFor="let calibre of calibres"
[checked]="calibre.isSelected"
[value]="calibre.value"
(change)="getCheckbox(calibre)"
class="example-margin mb-0 mt-1" >{{calibre.value}}</mat-checkbox>
</div>

Angular 6: How to build a simple multiple checkbox to be checked/unchecked by the user?

Here is a working example, where you can observe that an additional 'checked' value is added to each country, and bound to the value of each checkbox with [(ngModel)].

Stackblitz live example

template:

<p>
Test checkboxes
</p>

<div *ngFor="let country of countries; let i = index;">
<input type="checkbox" name="country{{country.id}}" [(ngModel)]="countries[i].checked">
<label for="country{{country.id}}">{{country.name}}</label>
</div>

<button type="button" (click)="sendCheckedCountries()" *ngIf="countries">Click to send the selected countries (see your javascript console)</button>

<p *ngIf="!countries">loading countries, please wait a second...</p>
<p *ngIf="countries">Debug info : live value of the 'countries' array:</p>

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

component :

//...
export class AppComponent implements OnInit {
public countries: Country[];

constructor(private countryService: CountryService) {}

public ngOnInit(): void {
// loading of countries, simulate some delay
setTimeout(() => {
this.countries = this.countryService.getCountries();
}, 1000);
}

// this function does the job of sending the selected countried out the component
public sendCheckedCountries(): void {
const selectedCountries = this.countries.filter( (country) => country.checked );
// you could use an EventEmitter and emit the selected values here, or send them to another API with some service

console.log (selectedCountries);
}
}

To use some proper TypeScript, I made an interface Country :

interface Country {
id: number;
name: string;
checked?: boolean;
}

I hope you get the idea now.

Note : the checked value is not "automatically there" at the beginning, but it doesn't matter.

When not there, it is the same as undefined, and this will be treated as false both in the checkbox and in the function that reads which country is checked.

For the "sending value" part :

The button will output the selected value to the browser's console, with some filter similar to what @Eliseo's answer suggests (I just used full country objects instead of ids)

For "real usecase" situation, you could use Angular's EventEmitters and have your component "emit" the value to a parent component, or call some service function that will make a POST request of your values to another API.



Related Topics



Leave a reply



Submit