Reputation: 26107
I have the following 4 checkboxes, generated dynamically. In the angular component, I would like to retrieve the "name", "value" and "state" of the checkbox.
HTML:
<input type="checkbox"
name="automotive"
value="car"
ngModel
(ngModelChange)="filterResults(obj, $event)">
<input type="checkbox"
name="automotive"
value="truck"
ngModel
(ngModelChange)="filterResults(obj, $event)">
<input type="checkbox"
name="apparel"
value="shirts"
ngModel
(ngModelChange)="filterResults(obj, $event)">
<input type="checkbox"
name="apparel"
value="pants"
ngModel
(ngModelChange)="filterResults(obj, $event)">
Component:
filterResults(obj: any, isChecked: boolean){
console.log(obj);
console.log(isChecked); // {}, true || false
}
I am able to get the state of the checkbox, but not the name and value. Upon printing to the console, obj
is undefined. I would like to apply filters to a dataset based on the name and value of the checkbox.
How do I get the name and value of the checked checkboxes, so I can do that?
Upvotes: 3
Views: 14915
Reputation: 837
I think that you can makes this:
<input type="checkbox"
name="automotive"
value="car"
ngModel
(ngModelChange)="filterResults({name: 'automotive', value: 'car'}, $event)">
<input type="checkbox"
name="automotive"
value="truck"
ngModel
(ngModelChange)="filterResults({name: 'automotive', value: 'truck'}, $event)">
<input type="checkbox"
name="apparel"
value="shirts"
ngModel
(ngModelChange)="filterResults({name: 'apparel', value: 'shirts'}, $event)">
<input type="checkbox"
name="apparel"
value="pants"
ngModel
(ngModelChange)="filterResults({name: 'apparel', value: 'pants'}, $event)">
Upvotes: 1
Reputation: 9380
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
Upvotes: 8
Reputation: 289
It would be better to know what version you are working on. This would be one of the approaches:
<input type="checkbox"
name="automotive"
value="car" (change)="checkValues($event)"
ngModel
(ngModelChange)="filterResults(obj, $event)">
and in the respective .ts file
checkValues(e: any) { console.log(e) }
You must find all the attributes you are looking for in the source property.
Upvotes: 1
Reputation: 322
You could add a dynamic id to each checkbox:
<input type="checkbox" [attr.id]="uniqueIdHere" ... >
Then access your checkbox properties like so:
var checkboxValue = (<HTMLInputElement>document.getElementById("uniqueIdHere")).value;
If your checkboxes are generated via a loop, you could use the index as part of the [attr.id]
Upvotes: 1