我正在开发Angular应用程序,其中我必须使用4个字段进行一些配置设置:
我想添加这些字段的多个集合并创建一个JSON结构。
尽管我能够动态添加字段,但是当我选择第n个部门名称时,相应的服务名称会覆盖所有(n-1)个“服务名称”字段。
这是我的component.html
文件:
//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>
我希望部门和服务名称字段正确映射。但是最新的一项是覆盖以前的条目。
答案 0 :(得分:0)
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));
}
答案 1 :(得分:0)
我可以通过进行以下更改来解决此问题:
component.html
中: //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,**i** )">
// 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 **fnServiceList(i)**" [value]="service.wfName">{{service.description}}</option>
</select>
</div>
</div>
component.ts
中:// New function added to return array element of current index
**fnServiceList(row){
return this.serviceList[row];
}**
// Added row as input to assign the output to current index of array
getServices = function (dept, **row**) {
// Fetch the services for given department in "services" variable
this.serviceList**[row]** = services;
// Instead of: "this.serviceList = services;"
}