使用 angular 动态添加面板
dynamically add panel using angular
我正在尝试动态添加面板,这里是我当前的静态面板,它有一些字段。但在动态面板中,最初它将是空面板。
这是我当前的 HTML 当我点击添加按钮时我需要添加一个面板时的样子
<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>
这是我尝试在联系面板旁边添加面板的参考图片
这是ts代码
add() {
this.form.addControl("abc", new FormGroup({}));
this.formData.groups = [...this.formData.groups, {
formGroupName: "abc",
fields: []
}]
};
但是这段代码没有按预期工作这里有问题
我认为这可能是因为您没有不可变地修改数组。每次修改数组或对象时,都要对其进行不可变的修改,以便更改检测知道数组的值发生了变化。要不可变地修改,我们必须改变数组在内存中的地址。
尝试:
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);
}
我正在尝试动态添加面板,这里是我当前的静态面板,它有一些字段。但在动态面板中,最初它将是空面板。
这是我当前的 HTML 当我点击添加按钮时我需要添加一个面板时的样子
<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>
这是我尝试在联系面板旁边添加面板的参考图片
这是ts代码
add() {
this.form.addControl("abc", new FormGroup({}));
this.formData.groups = [...this.formData.groups, {
formGroupName: "abc",
fields: []
}]
};
但是这段代码没有按预期工作这里有问题
我认为这可能是因为您没有不可变地修改数组。每次修改数组或对象时,都要对其进行不可变的修改,以便更改检测知道数组的值发生了变化。要不可变地修改,我们必须改变数组在内存中的地址。
尝试:
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);
}