dynamically add panel using angular

Viewed 180

I am trying to add panel dynamically here is my current static panel which is having some fields. But in dynamic panel initially it will be empty panel.

Here is my current HTML look like when i click add button i need to add one panel

<button class="addSection" title="Add Section" (click)="add()"></button>

<form [formGroup]="form" (ngSubmit)="onSubmit()">
<ng-container *ngFor="let group of formData.groups">
    <!-- Panels-->
    <mat-accordion>
        <mat-expansion-panel cdkDrag>
            <mat-expansion-panel-header>
                {{group.formGroupName}}
            </mat-expansion-panel-header>
            <div [formGroupName]="group.formGroupName">
                <div class="row" style="margin-left:20px;">
                    <ng-container *ngFor="let field of group.fields">
                        <!--Field Rows-->
                            Data
                        <!--Fields-->
                    </ng-container>
                </div>
            </div>
        </mat-expansion-panel>
    </mat-accordion>

</ng-container>

Here is the reference Image i am trying to add panel next to contact panel

enter image description here

Here is the ts code

 add() {
this.form.addControl("abc", new FormGroup({}));
this.formData.groups = [...this.formData.groups, {
  formGroupName: "abc",
  fields: []
 }] 

};

But this code is not working as expected something wrong here

1 Answers

I think this could be because you're not modifying the array immutably. Every time you modify an array or an object, modify it immutably so change detection is aware that the value of the array changed. To modify immutably, we have to change the address of the array in memory.

Try:

add() {
     console.log("add called");
     this.arr = this.myForm.get('arr') as FormArray;
     this.arr [...this.arr, ...this.createItem()];
     console.log(this.arr);
     // I think concat is immutable (returns a new array) so this should be fine
     this.panels = this.panels.concat(this.panels.length + 1);         
   }
Related