I have a form where I have checkboxes and I want to send it to an API in order to save it to a database.
This is the city.page.html
<ion-item *ngFor="let city of cities;">
<ion-checkbox [(ngModel)]="city.id" ></ion-checkbox>
<ion-label>{{city.name}}</ion-label>
</ion-item>
<ion-button type="button" (click)="saveCity()">Save</ion-button>
This is the city.page.ts
city: any;
saveCity() {
let data = {city: this.city};
this.http.post('http://example.com/api/saveCity', JSON.stringify(data))
.subscribe((res: any) => {console.log("success");});
}
The problem is that I don't know how to send that data in the below format because the API only accepts this format to save it into the database.
"city": [
"32",
"432",
"231"
]
Any help to make it possible will be appreciated.
CodePudding user response:
check this solution i don't know it is the best solution, maybe you could do in a more fancy way , but its works and solve your problem:
First on city.page.html, change the model and bind to a new one that will save the state of individual checkbox of the list , then add the value tag
<ion-item *ngFor="let city of cities;">
<ion-checkbox [(ngModel)]="selectedCities[city.id]" value="city.id"></ion-checkbox>
<ion-label>{{city.name}}</ion-label>
</ion-item>
<ion-button type="button" (click)="saveCity()">Save</ion-button>
then in cites.page.ts , just add a new property that will manage the states of the checkboxs:
selectedCities = {};
and then in your save method do this, you will filter the object keys that only have true(selected ones) and you will obtein the selected options as array:
saveCity() {
console.log(this.selectedCities);
const array = Object.keys(this.selectedCities).filter((key)=> {return this.selectedCities[key]});
console.log(array);
}
that's all , have a great day dude xD
link to working demo demo link , link to edit mode demo link edition mode