I am passing values on checkbox chnages event in api.
I want to pass comma seprated values in URL on checkbox change like below example.
code=ABC,DEF,RED
and remove values on checkbox unchecked event like below example code=ABC,DEF
Can any one help me to do this.
Below is my code
onChange(event, Code) { if (event.checked) { this.newCode = Code; } else { this.newCode = ''; } }
Advertisement
Answer
Simple solution could be.
in component.ts file
code: string; selectedValues = []; selectCheckBox(evt, val) { const status = evt.target.checked; if (status) { this.selectedValues.push(val) } else { this.selectedValues = this.selectedValues.filter((v) => v!==val) } this.code = this.selectedValues.join(',') } onSubmit() { let url = 'api.example.com/'; url = `${url}/&code=${this.code}`; console.log(url); // write you logic call api etc }
In template
<ul> <li><input type="checkbox" name="chbx1" value="AB" (change)="selectCheckBox($event, 'AB')"></li> <li><input type="checkbox" name="chbx2" value="CD" (change)="selectCheckBox($event, 'BC')"></li> <li><input type="checkbox" name="chbx3" value="ED" (change)="selectCheckBox($event, 'CD')"></li> </ul> <button type="button" (click)="onSubmit()">Submit</button>
Working DEMO
Hope this solve your issue.