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

Lak*_*ngh 7 angular2-forms angular

我正在处理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"])
    });
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

yur*_*zui 13

一种方式是这样的:

1)FormArray使用false默认值设置字段

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))
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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))
});
Run Code Online (Sandbox Code Playgroud)

Plunker示例

  • 我不想要这种类型的输出(“cities”:[true,true,true,true]),我想要(“cities”:[“Mohali”,“Amritsar”])。 (2认同)

Tzv*_*nov 7

我非常喜欢@yurzui 的答案,但是在获取值时遇到了问题..所以..

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

formArrayName=“通知”

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

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

最后,您将使用要保存/更新的原始记录 ID 数组来保存表单。 用户界面视图

表单json的相关部分

很乐意提出任何改进意见。

这是要点