【问题标题】:How to store multiple checkbox values in reactive form in angular2?如何在angular2中以反应形式存储多个复选框值?
【发布时间】:2017-12-29 13:09:55
【问题描述】:

我正在开发 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>

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

【问题讨论】:

  • 应该检查哪些项目?
  • 我更新了我的问题。

标签: angular angular2-forms


【解决方案1】:

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

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

formArrayName="通知"

(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 数组保存表单以保存/更新。

很高兴有任何改进意见。

这里是Gist

【讨论】:

    【解决方案2】:

    一种方法是这样的:

    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

    【讨论】:

    • 我不想要这种类型的输出 ("cities": [true, true, true, true]),我想要 ("cities" : ["Mohali", "Amritsar"]) .
    • @LakhvirSingh 尝试提交按钮
    • 感谢它的工作,但您使用变量来存储 defaultCities 和 defaultZipCodes 但在我的情况下,我不知道我会从 api 获取城市数组,因为每个数组及其 html 都是基于 api 响应生成的.如果我在 api 中获取城市数组,那么它将自动生成其 html 并在表单中添加新控件。
    • @LakhvirSingh 我仅使用变量作为示例。您可以在从服务器获取后更新值 this.form.get('cities').patchValue(this.cities.map(x => citiesFromServer.indexOf(x) > -1)); plnkr.co/edit/M5mIx5idfUDpRmiaxCPk?p=preview
    • 如果我在两个字段(城市、邮政编码)上分别使用 Object.assign(),如何获取表单值。因为当我在两个字段上分别使用时,我一次只能获得一个字段值,但我希望两个字段值一起但分别使用 Object.assign()。
    猜你喜欢
    • 2017-08-20
    • 2023-03-25
    • 2017-08-22
    • 2017-07-19
    • 1970-01-01
    • 2017-11-17
    • 2021-06-25
    • 2017-11-13
    • 2016-02-20
    相关资源
    最近更新 更多