在我检查或取消选中Angular 4应用程序中的复选框时,值会自动更改

时间:2017-09-29 12:19:21

标签: angular angular2-forms angular4-forms

我正在开发一个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.我不明白问题

0 个答案:

没有答案