0

Im trying to dynamically add and remove formgroup to a formarray using a counter component. There are 4 counter components in a for-loop which have a category. When the user clicks on add button, the counter increments and adds a formgroup to the formarray. No problem there.

But now I'm stuck with deleting the right formgroup. When a user clicks on the delete button on the formgroup or decrements the counter I want to remove the right group. So on decrement I need the last formgroup in that category to be deleted, and on on delete button click, I want the counter to decrement 1 and remove the formgroup.

This is what I have so far:

form component

 profileForm: FormGroup;

ngOnInit() {
    this.profileForm = this.fb.group({
      Age: new FormControl(0),
      PartnerAge: new FormControl(0),
      Children: this.fb.array([]),
    });
  
  }

 childRange = ScheidenChildRange;
  childList = [
    this.childRange.ZeroToThree,
    this.childRange.FourToTwelve,
    this.childRange.ThirteenToSeventeen,
    this.childRange.OlderThanEighteen,
  ];

get ChildrenArray() {
    return this.profileForm.get("Children") as FormArray;
  }

  initChildRow(age) {
    return this.fb.group({
      Age: new FormControl(age),
      BSOOrVSO: new FormControl(null),
      BSOOrVSOCostsPerMonth: new FormControl(null),
      BSOOrVSOHoursAWeek: new FormControl(null),
      Childminder: new FormControl(null),
      ChildminderCostsPerMonth: new FormControl(null),
      ChildminderHoursAWeek: new FormControl(null),
      FormalChildcare: new FormControl(null),
    });
  }

  addChild(count: number, childRange: ScheidenChildRange) {
    this.ChildrenArray.push(this.initChildRow(childRange));
    this.onInputChange.next();
  }

  removeChild(age: any) {
    const index = this.ChildrenArray.controls.findIndex(
      (c) => c.value.Age === age.index
    );
    this.ChildrenArray.removeAt(index);
    this.removeEvent.next(age);
    this.onInputChange.next();
  }

        <counter *ngFor="let child of childList | keyvalue; index as i" (incremented)="addChild($event, child.value)"
          (decremented)="removeChild($event)" [decrementEvent]="removeEvent.asObservable()" [index]="i" [max]="5"
          [label]="child.value | getChildRange">
        </counter>


    <div formArrayName="Children">
      <ng-container *ngFor="let child of ChildrenArray.controls; index as i">
        <child-questions *ngIf="child.get('Age').value === 0 || child.get('Age').value === 1"
          [Descriptions]="Descriptions" [formGroupName]="i" [Index]="i" [form]="child"
          (removeChildEv)="removeChild($event)" (inputChanged)="radioChecked()">
        </child-questions>

counter component

increment() {
    if (this.counter === this.max) {
      return;
    }
    this.counter += 1;
    this.incremented.emit({ count: this.counter, index: this.index });
  }

  decrement() {
    if (
      (!this.negativeAllowed && this.counter === 0) ||
      this.counter < this.min
    ) {
      return;
    }
    this.counter -= 1;
    this.decremented.emit({ count: this.counter, index: this.index });
  }

  constructor() {}

  ngOnInit() {
    if (this.decrementEvent) {
      this.eventsSubscription = this.decrementEvent.subscribe((data) => {
        console.log("Counter", data);
        if (this.index === data.index) {
          this.decrement();
        }
      });
    }
  }

  @HostListener("unloaded")
  ngOnDestroy(): void {
    this.eventsSubscription.unsubscribe();
  }
1
  • Can you create stackblitz link with your issue? it would be easier to understand Commented Sep 2, 2020 at 11:45

1 Answer 1

0

To remove FormGroup from FormArray, simply pass the FormGroup index to the function.

In the template:

    <div formArrayName="Children">
  <ng-container *ngFor="let child of ChildrenArray.controls; index as i">
    <child-questions *ngIf="child.get('Age').value === 0 || child.get('Age').value === 1"
      [Descriptions]="Descriptions" [formGroupName]="i" [Index]="i" [form]="child"
      (removeChildEv)="removeChild($event,i)" (inputChanged)="radioChecked()">
    </child-questions>

In the removeChild function:

removeChild(age: any, index: number) {
  this.ChildrenArray.removeAt(index);
  this.removeEvent.next(age);
  this.onInputChange.next();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.