-1

when i select check box its value is displayed as another array and does not get updated according to the for,the userdays work only when it is outside the employee form, how do i make it work when put inside the employee form, under skills[]

https://stackblitz.com/edit/angular-cueihr

enter image description here

4
  • Do you want workdays to be under each group below skills? Eg.., in the above given image, do you want the userdays array to be included in all three if the add button clicked thrice?? Commented Apr 1, 2020 at 13:44
  • yes, exactly that, my code is working when userdays is outside employees, but when i put it in employees array, it does not work Commented Apr 2, 2020 at 9:35
  • You could use this as reference stackblitz.com/edit/angular-teegvs Need to make unique control for userdays. to save the data in each individual item which now only works in first. Commented Apr 2, 2020 at 9:37
  • yea it only works for first, what do u mean by unique control? Commented Apr 2, 2020 at 9:45

1 Answer 1

1

Since you want to add userdays array inside each formgroup, First create userdays array of control inside newEmployee FormGroup.

component.ts

newEmployee(): FormGroup {
    return this.fb.group({
      firstName: '',
      lastName: '',
      repeat_sun: false,
      repeat_mon: false,
      repeat_tue: false,         
      skills:this.fb.array([]),
      userdays: this.fb.array([])
    })
 }

Then pass selected employees formGroup index from html.

<label class="checkbox-inline" *ngFor="let day of days; ">
    <input type="checkbox" formControlName="{{ day.name }}" name="{{ day.name }}"
        (change)="onChange(empIndex,day.value , $event.target.checked)" />{{ day.value }}
</label>

Finally add your logic as per your need.

component.ts

onChange(empIndex, day: string, isChecked: boolean) {
    const dayFormArray = (this.empForm.get("employees") as FormArray)
      .at(empIndex)
      .get("userdays") as FormArray;
    if (isChecked) {
      dayFormArray.push(new FormControl(day));
    } else {
      let index = (dayFormArray.value as []).findIndex(item => item === day);
      dayFormArray.removeAt(index);
    }
  }

Forked Example

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

2 Comments

Thanks for the answer bro.. I should passed empIndex to onChange function instead of using this.empForm.get("employees").value[0] it should be this.empForm.get("employees").value[empIndex] in the link I provided in comment section..
You are welcome bro. Yes you made small mistake sometime happens.

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.