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

时间:2017-07-24 03:40:30

标签: angular angular2-forms

我正在处理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,当我在表单字段中有默认值时,将自动检查数组中的值。

2 个答案:

答案 0 :(得分:11)

一种方式是这样的:

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))
});

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

答案 1 :(得分:1)

我非常喜欢@yurzui的答案 但有一个问题,让价值回来..所以......

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

  

formArrayName =&#34;通知&#34;

     

(更改)=&#34; updateChkbxArray(n.id,$ event.checked,&#39;通知&#39;)&#34;

这样它可以在一个表单中用于多个复选框数组。 只需设置每次连接的控件数组的名称。

&#13;
&#13;
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);
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

最后,您将保存包含原始记录ID数组的表单以进行保存/更新。 The UI View

The relevat part of the json of the form

  

很高兴有任何改进的评论。

以下是Gist