Reputation: 37
A dynamic checkbox is created from the list of cartoonData. On selecting each cartoon in a checkbox, I need to read the values in typescript function.
In HTML File
<div *ngFor="let cartoon of cartoonsData">
<input type="checkbox" (change)="onChange($event)" />
<label for="checkbox" >{{ cartoon.name }}</label>
</div>
In Typescript file
onChange(event){
//Code to get the checked values
}
Upvotes: 0
Views: 2551
Reputation: 57909
If we want an array with the "value"
cartoonsData=[{name:'one'},{name:'two'},{name:'three'}]
result:any=[]
@ViewChildren('checkbox') checkboxes!: QueryList<ElementRef>;
onChange(event){
const checkedItems = this.cartoonsData.filter((x,index)=>
this.checkboxes.find((c,i)=>i==index).nativeElement.checked)
.map(x=>x.name)
this.result=checkedItems;
}
If the data goes from a service we can subscribe in ngOnInit (but don't forget unsubscribe)
ngOnInit()
{
this.subscription=this.dataService.getData().subscribe((res:any[])=>{
this.cartoonsData=res;
})
}
ngOnDestroy()
{
this.subscription.unsubscribe()
}
Another option is use pipe async, but we need store in an array the result of the observable. So we can define an observable like
obs$=this.service.getData().pipe(tap((res:any)=>this.cartoonsData=res))
And use in .html
<div *ngFor="let cartoon of obs$|async">
...
</div>
There'e no problem because the "pipe(tap)" fill our auxiliar variable. see this stackblitz. (instead create a service simply I create an object with the property getData())
Upvotes: 1
Reputation: 36289
First add a reference on the input such as #checkbox
:
<div *ngFor="let cartoon of cartoonsData">
<input #checkbox type="checkbox" (change)="onChange($event)" />
<label for="checkbox" >{{ cartoon.name }}</label>
</div>
Next use @ViewChildren()
to reference the template reference. Then wherever you need to access the checked items you can use a filter
on the elements. You could also convert this to its own function if you need to use it often.
@Component()
export class MyComponent {
@ViewChildren('checkbox') checkboxes!: QueryList<ElementRef<HTMLInputElement>>;
onChange(event){
// To get the elements
const checkedItems = this.checkboxes.filter(box => box.nativeElement.checked);
// To get the actual values instead of just the element
// const checkedItems = this.cartoonsData.filter((x,index)=>this.checkboxes.find((c,i)=>i==index).nativeElement.checked).map(x=>x.name);
}
}
Upvotes: 3