What is the best way to retrieve the selected values from a checkbox using Angular?

I am working on creating a dynamic checkbox from a list of cartoon data. Each checkbox represents a cartoon, and when selected, I need to be able to read the values in a TypeScript function.

In my HTML file

<div *ngFor="let cartoon of cartoonsData">
    <input type="checkbox" (change)="onChange($event)" />
    <label for="checkbox" >{{ cartoon.name }}</label>
</div>
In my TypeScript file

onChange(event){
//Code to retrieve the checked values
}

Answer №1

To start, include a reference on the input like this #checkbox:

<div *ngFor="let cartoon of cartoonsData">
    <input #checkbox type="checkbox" (change)="onChange($event)" />
    <label for="checkbox" >{{ cartoon.name }}</label>
</div>

Then utilize @ViewChildren() to refer to the template reference. From there, whenever you need to access the checked items, implement a filter operation on the elements. If necessary, you can also transform this into its own function for repeated use.

@Component()
export class MyComponent {
  @ViewChildren('checkbox') checkboxes!: QueryList<ElementRef<HTMLInputElement>>;

  onChange(event){
    // To retrieve the elements
    const checkedItems = this.checkboxes.filter(box => box.nativeElement.checked);

    // To obtain the actual values rather than just the element
    // const checkedItems = this.cartoonsData.filter((x,index)=>this.checkboxes.find((c,i)=>i==index).nativeElement.checked).map(x=>x.name);
  }
}

Answer №2

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Make sure to wait for all API requests to finish before processing input in the textbox using Angular

When validating a number's existence in our database using an API, I trigger the API call on the (input) event of a textbox. For example, if I enter '1234' in the input box, the API will make four separate calls: first for '1', sec ...

What is the best way to have a variable adjust each time a coin is inserted until it reaches a specific value?

I have developed a unique coin box that recognizes the value of each coin inserted. Users can now pay for a service that costs 2.0 € by inserting coins of various denominations such as 2.0 €, 1.0 €, 0.50 €, 0.20 €, and 0.10 €. In my react-nati ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

Matching TypeScript against the resulting type of a string literal template

My type declaration looks like this: type To_String<N extends number> = `${N}` I have created a Type that maps the resulting string number as follows: type Remap<Number> = Number extends '0' ? 'is zero' : Number ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Adding a separator for thousands on data labels in ng2-charts

Take a look at this demonstration: http://embed.plnkr.co/7fGsiuRjcF0M0Ffeoml2/ If I modify the data to be: data: [2000, 3000, 4000, 8000, 12000, 12850] Can I add thousand separators to the dataset label? For example: 5,000 10,000 15,000 ...

Component in Next.js fetching data from an external API

I am attempting to generate cards dynamically with content fetched from an API. Unfortunately, I have been unsuccessful in finding a method that works during website rendering. My goal is to pass the "packages" as properties to the component within the div ...

Is it possible for TypeScript to manage a dynamic return type that is not determined by a function parameter?

I am facing a challenge with dynamic type checking using a param type and seeking help to solve it. Even though it might be a difficult task, any assistance would be greatly appreciated! Consider the following code: class DefaultClass { defaultProp: n ...

"Unlocking the full potential of Typescript and Redux: Streamlining the use of 'connect' without the need to

I am facing some challenges with typescript and redux-thunk actions. The issue arises when my components heavily rely on react-redux connect to bind action creators. The problem occurs when I create the interface for these redux actions within the compone ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...

Update ngModel value following the PUT request response

I currently have a variable named dummy_value and I would like to update it using an input box. <p>{{dummy_value}}</p> <input [(ngModel)]="dummy_value" /> Upon making this change, the dummy_value updates instantly due to the two-way bin ...

TypeScript error TS2531: Object may be null

<div > <input type="file" id="uploadImage"/> <button @click="Upload" style="width: 80px;height: 30px;" > upload ...

Serialization of AspNetCore EntityModel to Json is not possible

I am currently tackling a project in AspNetCore involving EntityFrameworkCore and I am looking to utilize Ajax to retrieve an object. However, my controller is encountering issues when trying to serialize this object into Json format, causing my Ajax call ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Sign up for a variety of HTTP observables subscriptions

I have a collection of Observables stored in activatedRoute.data.example and I need to listen for the most recent value emitted. private data$ = forkJoin( this.activatedRoute.data.pipe( map(({ examples }) => examples) ) ); ngOnInit(): void { ...

Executing angular 1 and angular 4 simultaneously within one browser tab

Is there a way to open my AngularJS 1 app running on port 3020 and an angular 4 app on port 4200 in the same tab by clicking a link? ...

What is the process for extracting the "path expression" from an interface in TypeScript?

My goal is to achieve the following structure: type Post = { id: number title: string author: { name: string } comments: { text: string }[] } type ExtractPathExpressions<T> = ??? type Paths = ExtractPathExpressions<Post> / ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

What is the syntax for typing a mongoose populated field in Typescript?

I am faced with a field that can either be an ID or have a value, and I am attempting to type this field using TypeScript import { InferSchemaType, Schema, Types, model } from 'mongoose'; const personSchema = new Schema({ _id: Schema.Types.Obj ...

Transform the property of type any/unknown into a specific generic type T within the map

Suppose I start with... type TypeNonGeneric = { prop1: any, prop2: string }; How do I transform it into... type TypeGeneric<T> = { prop1: T, prop2: string }; I have reviewed the documentation and it appears that I need to create a new generic type ...