如何在angular2中以反应形式存储多个复选框值?

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

我正在开发 angular2 应用程序并在表单字段中存储多个复选框的值时遇到问题。

类型脚本

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>

我想在表单字段中存储选中的城市和 zip_codes,当我在表单字段中有默认值时,数组中的值将被自动检查。

一种方法是这样的:

1) 使用 false 默认值

设置 FormArray 字段
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) 模板将如下所示:

<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) 提交表单

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) 默认值

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

非常喜欢@yurzui的回答 但是在取回值时遇到问题..所以..

我的解决方案 - 使用 Material View
解决了 Angular 5 连接是通过

formArrayName="notification"

(change)="updateChkbxArray(n.id, $event.checked, 'notification')"

这样它可以以一种形式用于多个复选框数组。 只需设置每次连接的控件数组名称即可。

constructor(
  private fb: FormBuilder,
  private http: Http,
  private codeTableService: CodeTablesService) {

  this.codeTableService.getnotifications().subscribe(response => {
      this.notifications = response;
    })
    ...
}


createForm() {
  this.form = this.fb.group({
    notification: this.fb.array([])...
  });
}

ngOnInit() {
  this.createForm();
}

updateChkbxArray(id, isChecked, key) {
  const chkArray = < FormArray > this.form.get(key);
  if (isChecked) {
    chkArray.push(new FormControl(id));
  } else {
    let idx = chkArray.controls.findIndex(x => x.value == id);
    chkArray.removeAt(idx);
  }
}
<div class="col-md-12">
  <section class="checkbox-section text-center" *ngIf="notifications  && notifications.length > 0">
    <label class="example-margin">Notifications to send:</label>
    <p *ngFor="let n of notifications; let i = index" formArrayName="notification">
      <mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>
    </p>
  </section>
</div>

最后,您要将带有原始记录 ID 数组的表单保存到 save/update。

Will be happy to have any remarks for improvement.

这是Gist