0

我正在开发一个 Angular 4 应用程序。

当我更改表单数组中的汽车数量时,它会自动更改表单数组中存在的每张卡片的数量。

HTML

<ng-container *ngFor="let car of cars">
   <div>
      <input type="checkbox" *ngIf="isCarChecked(car)" checked="checked" (change)="onCarChange(car, $event.target.checked)" >
      <input type="checkbox" *ngIf="!isCarChecked(car)" (change)="onCarChange(car, $event.target.checked)" >
      <span>{{car.name}}</span>
      <span>
         <button type="button" (click)="onCarCountChange(car, 'decrement')">-</button>
         <input type="number" [value]="countValueBinding(car)" (focusout)="onCarCountChange(car,$event.target.value)">
        <button type="button" (click)="onCarCountChange(car, 'increment')">+</button>
       </span>
    </div>
 </ng-container>

打字稿

car : FormGroup;    
carsArray =[{"name": "abc", "count": 3 }, {"name" : 4}];
constructor( private formBuilder : FormBuilder){}
    ngOnInit() {
      this.carForm = this.formBuilder.group({});
      this.createCarControlInForm();
    }


createCarControlInForm()
{
  this.carForm.addControl(cars, new FormControl());
}

onExcludesChange(car, isChecked){
  let carFormArray = <FormArray>this.carForm.controls.cars;
  if(isChecked){
     let control = this.formBuilder.group({
        name          : [car.name],
        count         : [car.count]
     });
     carFormArray.push(control);
  }
  else{         
     (this.carForm.controls['cars'].value).forEach((value, i) => {
        if(value.name == car.name){
           carFormArray.removeAt(i);
        }
     });
  }
}

public isCarChecked(car: any){
  let isChecked = false;
  for(let value of this.carForm.value['cars']){
     if(value && (value.name == car.name)){
        isChecked = true;
     }
  }
  if(isChecked){
     return true; 
  }else{ 
     return false; 
  }
}

onCarCountChange(car,value){
      for(let carValue of this.carForm.controls['cars'].value) {
         if(carValue.name == car.name){
            if(value == 'decrement')
            {
               if(+(carValue.count) > 1){
                  carValue.count = +(carValue.count) - 1;
               }
            }else if(value == 'increment'){
               carValue.count = +(carValue.count) + 1;
            }else{
               carValue.count = value;
            }
         }
      };
   }

countValueBinding(car){
      for(let carValue of this.carForm.controls['cars'].value) {
         if(carValue.name == car.name){
            return carValue.count;
         }
      }
   }

使用此代码,一切正常,当我单击复选框时,在表单中输入一个新控件,但问题是单击复选框时,即使选中/取消选中它也会使其他汽车计数为 1。我不明白这个问题。

4

0 回答 0