简体   繁体   中英

How to get the checked values from a checkbox in Angular?

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
}

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);
  }
}

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM