I have a form with checkbox names say Apple and Mango. When I check one/both/none I would like the value to store in a JSON on submitting the form.
How to do the same in Angular 5?
Here's how you can achieve it by Reactive Form:
xxx.component.html
<div [formGroup]="form" (ngSubmit)="onSubmit()">
<div>
<input type="checkbox" formControlName="apple">
<input type="checkbox" formControlName="mango">
</div>
<button type="submit">Submit</button>
</div>
xxx.component.ts
form = this.fb.group({
apple: true, // initial value
mango: false
}
);
onSubmit() {
console.log(this.form.value); // this is JSON
}
If you want to store string Apple or Mango you can validate the boolean results returned from this.form.value