在formarray angular中动态添加和删除formgroup

问题描述

我正在尝试使用计数器组件向formarray动态添加删除formgroup。 for循环中有4个计数器类别,它们具有一个类别。当用户单击添加按钮时,计数器将递增并将一个表单组添加到表单数组。没问题。

但是现在我要删除正确的表单组。当用户单击表单组上的删除按钮或递减计数器时,我想删除正确的组。因此,在递减时,我需要删除该类别中的最后一个表单组,在单击删除按钮时,我希望计数器递减1并删除该表单组。

这是我到目前为止所拥有的:

表单组件

 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>

计数器组件

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();
  }

解决方法

要从 FormArray 中删除 FormGroup,只需将 FormGroup 索引传递给函数即可。

在模板中:

    <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>

在removeChild函数中:

removeChild(age: any,index: number) {
  this.ChildrenArray.removeAt(index);
  this.removeEvent.next(age);
  this.onInputChange.next();
}