0

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>

Here is the output of the code and console also are in beside where I didn't get the proper value inside the skills[] array, I getting the result in CountryData[] outside the skills[] array but I need the value inside the skills[] array. How can this be possible?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • If you can mannage a multiple check-box, you can take a look to this SO:https://stackoverflow.com/questions/63797930/get-multiple-checkbox-value-as-an-array-in-angular/63799360#63799360, another way can be https://stackoverflow.com/questions/65731573/how-to-handle-multiple-checkboxes-with-angular-reactive-forms/65731876#65731876 – Eliseo Jan 19 '21 at 12:14

1 Answers1

0

You're pushing a new form control every time. shouldn't it be added to CountryData in skillsForm ?

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++;
  });
}
danish ali
  • 132
  • 1
  • 5