4

I am trying to show or hide the respective skillBox Element when we check/uncheck the checkbox. The issue is here, When I am doing so, All the skillBox are getting hide/show in the FormArray. Could you please help me to show or hide only the respective FormArray Element?

Here is the code.

 <div class="row box">
    <div class="col-xs-12">
        <h4>Reactive Test Form</h4>
        <button class="btn btn-info" type="button" (click)="fnOnAddProfile()">Add Profile</button>
    <hr> 
    <form [formGroup]="ourForm" (ngSubmit)="fnSave()">
     <div formArrayName="apps">
       <div class="inner-box" *ngFor="let app of ourForm.get('apps').controls; let ind = index" >
      <div [formGroupName]="ind" >
        <div formGroupName="common">
          <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" formControlName="name" />
        </div>
        <div class="form-group">
          <label for="name">Profession</label>
          <input type="text" class="form-control" formControlName="profession" />
        </div>
        <label for="skillcheckbox">
          <input type="checkbox" formControlName="enableSkill"
          (change)="fnGetCheckBoxVal(app.get('common').get('enableSkill').value, ind)" /> Want to add Skill?
        </label>
        </div>
        <div *ngIf="isSkill" id="skillBox">
          <div class="row" formArrayName="skills">
            <div class="col-xs-12">
              <div class="form-group" *ngFor="let control of getSkills(app); let i = index">
                <input type="text" class="form-control" [formControlName]="i">
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-xs-12">
              <h5>Please add your skills</h5>
              <button class="btn btn-primary" type="button" (click)="fnOnAddSkill(app,ind)">Add Skill</button>
            </div>
          </div>
        </div>
      </div>
       </div>
     </div>
      <hr>
      <div class="form-group">
        <button class="btn btn-success" type="submit">Save</button>
        &nbsp;
        <button class="btn btn-danger">Clear</button>
      </div>

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

Here is the typescript code

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, FormArray, Validators } from "@angular/forms";
@Component({
  selector: "app-reactive-forms",
  templateUrl: "./reactive-forms.component.html",
  styleUrls: ["./reactive-forms.component.css"]
})
export class ReactiveFormsComponent implements OnInit {
  ourForm: FormGroup;
  isSkill: boolean = false;
  defaultApps: FormGroup;
  constructor() { }

  ngOnInit() {

    this.defaultApps = new FormGroup({
      common: new FormGroup({
        name: new FormControl(null),
        profession: new FormControl(null),
        enableSkill: new FormControl(false)
      }),
      skills: new FormArray([])
    });
    this.initForm();
    //  this.fnGetCheckBoxVal();
  }

  initSkills() {
    return   new FormGroup({
      common: new FormGroup({
        name: new FormControl(null),
        profession: new FormControl(null),
        enableSkill: new FormControl(false)
      }),
      skills: new FormArray([])
    });
  }



  initForm() {
    this.ourForm = new FormGroup({
      "apps": new FormArray([
        this.initSkills()
      ])
    });
   // (this.ourForm.get('apps') as FormArray).push(this.defaultApps);

  }
  // get formSkills() {
  //   // return (<FormArray>this.ourForm.get("skills")).controls;
  //   return (app.get('skills') as FormArray).controls;
  // }
  getSkills(control: FormArray) {
return (control.get('skills') as FormArray).controls;
  }

  fnOnAddSkill(app: FormControl, ind: number) {
    console.log(ind);
    const control = new FormControl(null, Validators.required);
    const myForm = app.get("skills") as FormArray;
    myForm.push(control);
  }
  fnSave() {
    console.log(this.ourForm);
    // console.log(this.ourForm.get('common').get('enableSkill'));
  }
  fnGetCheckBoxVal(value, index) {
    //  //.get('common').get("enableSkill")
    //  (this.ourForm.get('apps') as FormArray).valueChanges.subscribe(value => {
    //    console.log(value);
    //     value ? (this.isSkill = true) : (this.isSkill = false);
    //   });
    console.log(value, index);
    value ? (this.isSkill = true) : (this.isSkill = false);
  }
  fnOnAddProfile() {
    (this.ourForm.get('apps') as FormArray).push(this.initSkills());
  }
}

Any help will be appreciated. Thanks in advance.

6
  • 1
    Welcome to Stack Overflow. You might get more response if you make this question shorter, probably by producing a shorter code example. Here are some guidelines: stackoverflow.com/help/mcve. Commented Feb 8, 2019 at 16:32
  • I'm sorry, I'm stupid, so I don't really get your question :D What exactly is the checkbox supposed to do? The problem is, on a check/uncheck it is hiding all the div box element in an array. - I don't understand that, you have one checkbox that controls the whole array, so assumingly it's hiding/showing all skills Commented Feb 8, 2019 at 17:12
  • Apology for the confusion. I am tring to apply ngIf only for the respective element in the array which is related to the check box which belongs to the same array element. Commented Feb 8, 2019 at 18:51
  • Aaah, look see, I said I am stupid. Now I see what you mean, didn't notice that there are several "profiles". Yeah, I understand now ;) Commented Feb 8, 2019 at 19:05
  • But anyway, you are using the same boolean flag isSkill, you need to make unique booleans for all your "profiles" Commented Feb 8, 2019 at 19:10

1 Answer 1

2

You are using the same boolean flag isSkill for all profiles, so when you toggle one checkbox, it will toggle all. The boolean flags need to be unique for each profile. I see that you already have a boolean form control enableSkill. You can utilize that, you then also do not need the change event. So remove fnGetCheckBoxVal(value, index) completely, and instead of:

<div *ngIf="isSkill" id="skillBox">

use:

<div *ngIf="app.get('common.enableSkill').value">

I don't know if when you toggle it off, you want to actually remove the skills that has been entered for a profile, but that is a separate question.

Here's a demo with the changes I made: StackBlitz

Sign up to request clarification or add additional context in comments.

6 Comments

PS. You are new, but aaalways try and make the question as short as possible, also if possible (which would have been here) create a demo showcasing your issue. This will help you get answers much faster. Long questions tend to scare people off, and they won't even take a second look. I usually don't either (anymore) But I was bored :D
I am really thankful for your instant answer. Sure Next time I will keep that in mind while posting a question. Thank you so much again.
You are very welcome. Have a grrreat weekend and happy coding! :)
AJIT_82 Thank you. You too.
And to add, a great positive for your question was, that although much code, you had all the code needed for me to be able test it. That isn't always the case, so that is a big plus! :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.