在数组中使用 Reactive Form 无法获得多复选框值

问题描述

import { Component } from '@angular/core';
import { FormGroup,FormBuilder,Validators,FormArray,FormControl,AbstractControl } from '@angular/forms';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
  skillsForm: FormGroup;
  isSubmitted = false;
  CountryData: Array<any> = [
    { name: 'IND',value: 'India' },{ name: 'AUS',value: 'Australia' },{ name: 'USA',value: 'America' },{ name: 'RUS',value: 'Rusia' },{ name: 'Eng',value: 'England' }
  ];

  City: any = ['Jamshedpur','Bhubaneswar','Cuttack','Bhillai','Patna','Agra','Ahmedabad','Bilaspur'];

  constructor(private fb: FormBuilder) {

    this.skillsForm = this.fb.group({
      fname: [''],lname: [''],email: [''],phn: [''],// checkArray: this.fb.array([],[Validators.required]),// checkArray: this.fb.array([]),CountryData: this.fb.array([]),// gender: new FormControl('',Validators.required),skills: this.fb.array([]),});

    this.skillsForm.valueChanges.subscribe((res) => {
      console.log(this.skillsForm,this.skillsForm.value);
      // console.log("SkillsForm");
    })

  }

  get skills(): FormArray {
    return this.skillsForm.get("skills") as FormArray
  }

  // get countryName(): FormArray {
  //   return this.skillsForm.get("skills") as FormArray
  // }

  get f() {
    return this.skillsForm.controls;
  }

  newSkill(): FormGroup {
    return this.fb.group({
      CountryData:'',gender: '',cityName: '',txtArea: '',})
  }

  addSkills() {
    this.skills.push(this.newSkill());
    // console.log("AddSkills");
  }

  removeSkill(i: number) {
    this.skills.removeAt(i);
    // console.log("Remove");
  }

  onSubmit() {
    console.log(this.skillsForm.value);
    // console.log("submit");

  }

  onCheckBoxChange(e: any) {
    const checkArray: FormArray = this.skillsForm.get('CountryData') as FormArray;

    if (e.target.checked) {
      checkArray.push(new FormControl(e.target.value));
      console.log("CheckBox");
    } 
      else {
        let i: number = 0;
        checkArray.controls.forEach((item: AbstractControl) => {
          if (item.value == e.target.value) {
            checkArray.removeAt(i);
            return;
        }
        i++;
      });
    }
  }







}
<form [formGroup]="skillsForm"  class="form-horizontal" (ngSubmit)="onSubmit()">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">Create Employee</h3>
    </div>

    <div class="panel-body">

      <div class="form-group">
        <label class="col-md-4 control-label" for="fname">First Name:</label>
          <div class="col-md-6">
          <input id="fname" formControlName="fname" type="text" class="form-control">
        </div>
      </div>

      <div class="form-group">
        <label class="col-md-4 control-label" for="lname">Last Name:</label>
          <div class="col-md-6">
          <input id="lname" formControlName="lname" type="text" class="form-control">
        </div>
      </div>

      <div class="form-group">
        <label class="col-md-4 control-label" for="email">Email:</label>
          <div class="col-md-6">
          <input id="email" formControlName="email" type="text" class="form-control">
        </div>
      </div>

      <div class="form-group">
        <label class="col-md-4 control-label" for="phn">Phone No:</label>
          <div class="col-md-6">
          <input id="phn" formControlName="phn" type="text" class="form-control">
        </div>
      </div>

   

<!-- This is the TEXT----!!!!!!-----======---########-----------AREA  Line -->

<!--------######################################################----->












<!-- This is the TEXT----!!!!!!-----======---########-----------AREA  Line -->
 


<!-- This is the TEXT----!!!!!!-----======---########-----------AREA  Line -->
<!-- This is the TEXT----!!!!!!-----======---########-----------AREA  Line -->





 <!-- This is the Comment Line -->
  <!-- This is the Comment Line -->
  <div class="form-group form-horizontal">
    <label class="col-md-4 control-label" for="address">Address:</label>

    <div class="col-md-6">
      <hr class="new4">
      </div>
    </div>
 <!-- This is the Comment Line -->
  <!-- This is the Comment Line -->




<div formArrayName="skills">

    <div *ngFor="let skill of skills.controls; let i=index">

        <div class="form-group">
          <div class="col-md-1"></div>
            <div class="col-md-9">
               <div [formGroupName]="i">

      <!-- This is the Modification AREA Line -->            

    <div class="form-group">
      <label class="col-md-4 control-label" for="cty">Select Country:</label>
        <div class="col-md-6">
          <div class="form-group">
            <div class="form-check form-check-inline">

       
               
                <div class="chk">
                  <div *ngFor="let CountryData of CountryData; let i=index">

                    <input class="checkBox-inline" type="checkBox" id="check" [value]="CountryData.value" (change)="onCheckBoxChange($event)"
                      formControlName="CountryData"/>
                          <label for="check" class="checkBox-inline">{{CountryData.value}}</label>

                  </div>
                </div>
                
               
            <div *ngIf="isSubmitted && f.gender.invalid" class="alert alert-danger">
              <div *ngIf="f.gender?.errors?.required">SELECT YOUR COUNTRY</div>
            </div>

         <!-- <div class="invalid-Feedback" *ngIf="isSubmitted && countryName?.errors?.required">
             <sup>*</sup>Please select your city name
        </div> -->


            </div>
          </div>

      </div>
    </div>




  <!-- This line For CheckBox -->
 <!-- This line For CheckBox -->

 <!-- This line For Radio -->
  <!-- This line For Radio -->
  <div class="form-group row">
    <label class="col-md-4 control-label" for="gender">Gender:</label>
      <div class="col-md-2 form-check form-check-inline">
        <input id="male" type="radio" value="male" name="gender" formControlName="gender">&nbsp;
        <label for="male">Male</label>

        <input id="female" type="radio" value="female" name="gender" formControlName="gender">&nbsp;
        <label for="female">Female</label>
      </div>

    <div *ngIf="isSubmitted && f.gender.invalid" class=".has-error">
      <div *ngIf="f.gender?.errors?.required">SELECT YOUR GENDER</div>
    </div>
  </div>
 <!-- This line For Radio -->
 <!-- This line For Radio -->


 <!-- This line .....................................................For Radio -->
 <!-- This line....................................................... For Radio -->

 

 <!-- TThis.................................................... line For Radio -->
 <!-- TThis ..................................................line For Radio -->

 <div class="form-group mb-3">
  <div class="col-md-4">

    <label class="float-right">
        City:
    </label>
  </div>
            <div class="row">
              <div class="col-md-4">
                <select class="custom-select" formControlName="cityName">
                  <option value="">Choose your city</option>
                  <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
                </select>

              <div *ngIf="isSubmitted && f.gender.invalid" class="alert alert-danger">
                <div *ngIf="f.gender?.errors?.required">PLEASE SELECT CITY</div>
              </div>
            </div>
          </div>

  </div>
  <!-------------TextArea-Address:---------------->
  <div class="form-group form-horizontal">
    <label class="col-md-4 control-label" for="address">Full-Address:</label>

    <div class="col-md-6">

   
        <div class="form-group green-border-focus">

         

          <textarea formControlName="txtArea" class="form-control" id="exampleFormControlTextarea5" rows="4" cols="50">


          </textarea>
        </div>
     

      </div>
    </div>

               
    
               </div>
          </div>
          <div class="col-md-1">
            <button class="btn btn-primary" [disabled]="!skillsForm.valid" (click)="removeSkill(i)"><i>-</i>DELETE</button> 

          </div>

        </div>
    </div>
</div>







  <!-- This is the Comment Line -->

    <div class="panel-footer d-flex justify-content-center">
    <button class="btn btn-primary" [disabled]="!skillsForm.valid" type="submit">Save</button> &nbsp;&nbsp;&nbsp;&nbsp;
    <button class="btn btn-primary" (click)="addSkills()" type="submit"><i>+</i>ADD</button> 
   </div>

 </div>
 </div>
</form>
 
     
 
<!-- {{this.skillsForm.value | json}} -->

<router-outlet></router-outlet>

这里是代码输出,控制台也在我没有在技能 [] 数组中获得正确值的地方旁边,我在技能 [] 数组之外的 CountryData[] 中获得了结果,但我需要Skills[] 数组中的值。这怎么可能?

解决方法

您每次都在推送一个新的表单控件。不应该在 SkillForm 中添加到 CountryData 吗?

onCheckboxChange(e: any) {
const checkArray: FormArray = this.skillsForm.get('CountryData') as FormArray;

if (e.target.checked) {
  checkArray.push(new FormControl(e.target.value));
  console.log("Checkbox");
} 
  else {
    let i: number = 0;
    checkArray.controls.forEach((item: AbstractControl) => {
      if (item.value == e.target.value) {
        checkArray.removeAt(i);
        return;
    }
    i++;
  });
}