我正在研究 Angular 反应式表单,我想将控件动态添加到 Angular 表单数组。但是当我添加一个选择框或文本区域时,之前添加的控件也会被新添加的控件替换。我认为我的 HTML 代码中存在一些问题:
<form [formGroup]="reviewForm" >
<span *ngIf="isClicked">
<div formArrayName="controlArray">
<div
class="form-group"
*ngFor="let control of reviewForm.get('controlArray').controls; let i = index">
<label>{{label}} </label>
<!-- {{selectedControl.attributes.value}} -->
<span *ngIf="!(selectbox || textarea);else dropdown">
<input
type="{{control.value}}"
class="form-control"
placeholder="abc"
[formControlName]="i"
>
</span>
<ng-template #dropdown>
<span *ngIf="selectbox;else comment">
<select
class="form-control"
[formControlName]="i">
</select>
</span>
<ng-template #comment>
<span *ngIf="textarea">
<textarea name="Comment" id="" cols="30" rows="10"></textarea>
</span>
</ng-template>
</ng-template>
</div>
</div>
</span>
<button type="button" (click)="addControl()">Add</button>
<!-- <button type="button" (click)="clicked()">Add</button><br /> -->
<!-- <button class="btn btn-primary" type="submit">Submit</button> -->
</form>
这是组件类代码:
addControl(){
this.isClicked = true;
const control = new FormControl(this.selectedControl.name, Validators.required);
(<FormArray>this.reviewForm.get('controlArray')).push(control);
switch(this.selectedControl.name){
case 'select':
this.selectbox = true;
break;
case 'textarea':
this.textarea = true;
break;
default:
break;
}
// console.log(this.selectedControl);
}
它是我项目的 stackblitz 演示网址: https ://stackblitz.com/edit/angular-mjiu8x
请帮忙。