首页 文章

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

提问于
浏览
3

我正在处理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 回答

  • 10

    我非常喜欢@yurzui的答案但是有一个问题就是重新获得 Value ..所以...

    我的解决方案 - 使用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的数组保存表单以进行保存/更新 .
    The UI View

    The relevat part of the json of the form

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

    这是Gist

  • 1

    一种方式是这样的:

    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

相关问题