Ask Your Question
2

What is the method to send an array of selected checkboxes from Angular to an API?

asked 2022-06-18 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-11-18 09:00:00 +0000

david gravatar image

One method to send an array of selected checkboxes from Angular to an API is by using the HTTP POST method.

Firstly, create an array to store the selected checkboxes, and bind each checkbox to a corresponding property in the array using ngModel. For example:

<form>
  <label *ngFor="let item of items">
    <input type="checkbox" [(ngModel)]="item.selected" name="selectedItems">{{ item.name }}
  </label>
  <button (click)="postSelectedItems()">Submit</button>
</form>

In the component, create a function to handle the HTTP POST request. This function should take the selected items array as a parameter, and send it to the API using the Angular HTTP service. For example:

import { HttpClient } from '@angular/common/http';

...

constructor(private http: HttpClient) {}

postSelectedItems(selectedItems: any[]) {
  this.http.post('https://example.com/api/items', selectedItems)
    .subscribe((response) => {
      console.log('response', response);
    });
}

When the submit button is clicked, the postSelectedItems() function will be called, and the selectedItems array will be sent to the API as a request body. The API can then process the array and return a response.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-18 11:00:00 +0000

Seen: 13 times

Last updated: Nov 18 '22