Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store multiple checkbox values in reactive form in angular2?

I am working on angular2 application and getting problem in storing values of multiple check boxes in form field.

Type script

form : FormGroup;
cities = ["Mohali", "Chandigarh", "Ludhiana", "Amritsar"];
zip_codes = ["282001", "456123", "123456", "140412"];

constructor(private formBuilder : FormBuilder)
{
    this.form = this.formBuilder.group({
       cities   : this.formBuilder.array(["Mohali", "Amritsar"]),
       zip_codes : this.formBuilder.array(["456123"])
    });
}

HTML

<div *ngFor="let city of cities">
    <input type="checkbox" formControlName="cities" value="city">
    <span>{{city}}</span>
</div>

<div *ngFor="let zipCode of zip_codes">
    <inbput type="checkbox" formControlName="zip_codes" value="zipCode">
     <span>{{zipCode}}</span>
</div>

I want to store checked cities and zip_codes in form field and when I have default values in form field then the values are in array will be checked automatically.

like image 403
Lakhvir Singh Avatar asked Jul 24 '17 03:07

Lakhvir Singh


People also ask

How do I save multiple checkbox values in react?

To save multiple checkbox values in React, convert the checkbox values to a string and filter the state, and if any of the checkbox values are true, we add to an array and then change that array into the string and send that data to the server.


1 Answers

One way would be like this:

1) Setup FormArray fields with false default values

this.form = this.formBuilder.group({
  cities   : this.formBuilder.array(this.cities.map(x => !1)),
  zip_codes : this.formBuilder.array(this.zip_codes.map(x => !1))
});

2) The template will look like this:

<div *ngFor="let city of cities; let i = index" formArrayName="cities">
  <input type="checkbox" [formControlName]="i">
  <span>{{city}}</span>
</div>

<div *ngFor="let zipCode of zip_codes; let i = index" formArrayName="zip_codes">
  <input type="checkbox" [formControlName]="i">
  <span>{{zipCode}}</span>
</div>

3) Submit form

convertToValue(key: string) {
  return this.form.value[key].map((x, i) => x && this[key][i]).filter(x => !!x);
}

onSubmit() {
  const valueToStore = Object.assign({}, this.form.value, {
    cities: this.convertToValue('cities'),
    zip_codes: this.convertToValue('zip_codes')
  });
  console.log(valueToStore);
}

4) Default values

const defaultCities = ["Mohali", "Amritsar"];
const defaultZipCodes = ["456123"];
this.form = this.formBuilder.group({
  cities: this.formBuilder.array(this.cities.map(x => defaultCities.indexOf(x) > -1)),
  zip_codes: this.formBuilder.array(this.zip_codes.map(x => defaultZipCodes.indexOf(x) > -1))
});

Plunker Example

like image 72
yurzui Avatar answered Sep 22 '22 08:09

yurzui