For those looking to create an array with the "value"
favoriteShows=[{name:'one'},{name:'two'},{name:'three'}]
result:any=[]
@ViewChildren('checkbox') checkboxes!: QueryList<ElementRef>;
onChange(event){
const selectedItems = this.favoriteShows.filter((x,index)=>
this.checkboxes.find((c,i)=>i==index).nativeElement.checked)
.map(x=>x.name)
this.result=selectedItems;
}
If the data is coming from a service, we can subscribe in ngOnInit (just remember to unsubscribe later)
ngOnInit()
{
this.subscription=this.dataService.getData().subscribe((res:any[])=>{
this.favoriteShows=res;
})
}
ngOnDestroy()
{
this.subscription.unsubscribe()
}
Another option is to use async pipe, but we must store the observable result in an array. So we define an observable like this:
obs$=this.service.getData().pipe(tap((res:any)=>this.favoriteShows=res))
And then utilize it in the HTML file
<div *ngFor="let show of obs$|async">
...
</div>
No need to worry because the "pipe(tap)" populates our auxiliary variable. Check out this stackblitz example. (Instead of creating a service, I simply used an object with a method called getData())