angular - Angular 7 : How to fix value overwriting during dynamic field addition?
问题描述
I am working on an Angular application, wherein I have to do some configuration setup using 4 fields:
- Department Name (drop down)
- Service Name (drop down)
- Status (text field)
- Level (text field).
I want to add multiple set of these fields and create a JSON structure.
- 'Department Name' and 'Service Name' values are fetched using API calls.
- 'Service Name' options is populated based on 'Department Name' selected.
Though I am able to add the fields dynamically, but when I select nth Department Name, corresponding Service Name overwrites all (n-1) 'Service Name' fields.
Here is my component.html
file:
//mapFormGroup returns FormArray for given set of fields
<div *ngFor="let map of mapFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row">
<label>Department Name</label>
// getServices fetches all services for selected department
<select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value)">
// deptList contains list of all departments
<option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
</select>
<label>Service Name</label>
<select class="form-control" formControlName="serviceName" type="text">
// serviceList contains list of all services for given department
<option *ngFor="let service of serviceList" [value]="service.wfName">{{service.description}}</option>
</select>
</div>
</div>
I expect correct mapping of Department & Service Name fields. But the latest one is overwriting previous entries.
解决方案
dataSource: ServiceName[]; // create class for service or can have just [];
ngOnInit(){
this.dataSource = [];
this.ServiceNameService.getServiceDetails().subscribe( resp => {
resp.forEach(element => {
console.log(element);
const config = new ServiceName(
element.ServiceId, element.Name); // this is constructor or if general array
//change accordingly
this.dataSource.push(config);
});
}
getServices(val){
this.ServiceNameList = this.dataSource.filter(obj =>
String(obj.DepartmentName).toUpperCase() === String(val));
}
推荐阅读
- ms-access - 表未使用 runsql 保存在 Access 中
- spring - 如何控制 Flux.flatMap (Mono) 的并行性?
- c# - 统一空中运动与速度变化
- maven - 与原始工件相同的 POM 父工件 ID 是
- reactjs - 如何添加图像 src 以响应状态和设置状态
- random - 在已知边界的图中查找随机 x,y 坐标
- regex - Java 日志的正则表达式模式
- python - 无法消除全局变量
- javascript - 使用 react-static-plugin-favicon 不显示 favicon
- javascript - 全屏切换时不要执行一段代码