首页 > 解决方案 > 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:

I want to add multiple set of these fields and create a JSON structure.

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.

标签: angulartypescriptangular7

解决方案


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));
}

推荐阅读