动态添加表单元素时遇到问题,在其中添加一组新元素会重置前一个元素的值。
再次添加另一组时,它会显示前一个选择的选定值,但是会清除前一个选择的选定值。 不过,这不会影响输入元素。
HTML code:
<div class="form-group" [formGroup]="delegateesForm">
<div formArrayName="items" *ngFor="let item of delegateesForm.get('items')?.controls; let i = index;">
<div class="input-group mb-2 mr-sm-2 mb-sm-0" [formGroupName]="i">
<mat-form-field class="mat-full-width">
<mat-select formControlName="delegateeEmployeeNumber" placeholder="Employee Number">
<mat-option *ngFor="let emp of employees" [value]="emp.employNumber">
{{ emp.employNumber }} {{ emp.firstName }} {{ emp.lastName }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="mat-full-width">
<input matInput formControlName="title" placeholder="Delegation Title">
</mat-form-field>
<mat-form-field class="mat-full-width">
<input matInput formControlName="comments" placeholder="Delegation Comments">
</mat-form-field>
</div>
<hr />
</div>
</div>
<button type="button" mat-raised-button (click)="addItem()" color="warn">Add Delegatee</button>
<hr />
Typescript code:
employees$: Observable<shared.Employee[]>;
employees: shared.Employee[];
delegateesForm: FormGroup;
delegateesItems: FormArray;
delegations: Array<any>;
delegationsEmployeesIds: Array<any>;
modelData;
.
.
.
constructor(private formBuilder: FormBuilder)
{
this.delegations = [];
this.delegationsEmployeesIds = [];
this.modelData=[];
}
...
ngOnInit() {
this.delegateesForm = this.formBuilder.group({
items: this.formBuilder.array([this.createItem()])
});
}
createItem(): FormGroup {
return this.formBuilder.group({
delegateeEmployeeNumber: "",
title: "",
comments: ""
});
}
addItem(): void {
this.employees$=undefined;
this.employees$=this.getEmployeesInDepartment();
this.employees$.subscribe(emps => {
this.employees=emps;
this.delegateesItems = this.delegateesForm.get("items") as FormArray;
this.delegateesItems.push(this.createItem());
console.log("this.delegateesForm.value ",this.delegateesForm.value);
this.modelData = Object.assign({}, this.delegateesForm.value);
Object.entries(this.modelData.items[0]).forEach(([key, val]) => console.log(`key val ${key}: ${val}`));
for(let i=0;i<this.employees.length;i++)
{
console.log(this.modelData);
if(this.modelData.items!==undefined)
{
const emp=this.employees[i];
this.modelData.items.forEach(delegatee => {
if(delegatee.delegateeEmployeeNumber===emp.employNumber)
{
this.employees.splice(i,1);
}
});
}
}
});
}
预期结果是,单击“添加代表”将创建一组新的输入元素,其中不包括以前选择的任何雇员。
但是,尽管输入始终保持其值不变,它始终会清除最近选择的选择值。