为了账号安全,请及时绑定邮箱和手机立即绑定

角如何获取多个复选框的值?

角如何获取多个复选框的值?

蝴蝶不菲 2019-12-02 13:09:13
我正在使用Angular中的复选框来选择多个数据,并尝试获取表单提交中复选框的值。而不是将值im作为真实值获取。我尝试了以下代码来帮助我提前感谢   export class CreatesessionComponent implements OnInit {          form : FormGroup ;      constructor(private formBuilder: FormBuilder) {             }              ngOnInit() {       this.form = this.formBuilder.group({               useremail :  new FormArray([            new FormControl('',Validators.required)          ])          });    }  }userdata是动态数组,我将从数据库中获取<div class = "row" formArrayName="useremail; let k = index">   <div class="col-md-8 col-sm-5 col-xs-12 col-lg-8">       <div *ngFor="let data of userdata">           <div class="col-md-6">               <input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}           </div>       </div>   </div></div> 
查看完整描述

3 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

由于您要使用多个值,因此需要使用FormArray,因为FormControl只能捕获一个值。


首先声明一个空的formArray:


this.myForm = this.fb.group({

  useremail: this.fb.array([])

});

迭代您的电子邮件,并查看change事件,并将相应的电子邮件和事件传递给onChange您检查方法是否为的方法checked,然后将相应的电子邮件添加到formarray,如果未选中,则从表单数组中删除所选的电子邮件:


<div *ngFor="let data of emails">

  <input type="checkbox" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>

</div>

和onChange:


onChange(email:string, isChecked: boolean) {

  const emailFormArray = <FormArray>this.myForm.controls.useremail;


  if(isChecked) {

    emailFormArray.push(new FormControl(email));

  } else {

    let index = emailFormArray.controls.findIndex(x => x.value == email)

    emailFormArray.removeAt(index);

  }

}


查看完整回答
反对 回复 2019-12-02
?
哔哔one

TA贡献1854条经验 获得超8个赞

如果您想使用form.reset()或form.patchValue()修改模型,则它将无法正常工作。要解决这些问题,您需要实现ControlValueAccessor接口。基本上,您需要创建2个组件:组组件,该组件保存模型值并实现ControlValueAccessor和复选框组件,即实际复选框。我写了一篇博客文章,上面有详细的解释,还创建了一个演示一些示例的插件。


最终用法:


<checkbox-group [(ngModel)]="selectedItems">

    <checkbox value="item1">Item 1</checkbox>

    <checkbox value="item2">Item 2</checkbox>

    <checkbox value="item3">Item 3</checkbox>

    <checkbox value="item4">Item 4</checkbox>

</checkbox-group>

组组件的实现:


@Component({

selector: 'checkbox-group',

template: `<ng-content></ng-content>`,

providers: [{

      provide: NG_VALUE_ACCESSOR,

      useExisting: forwardRef(() => CheckboxGroupComponent),

      multi: true

    }]

 })

export class CheckboxGroupComponent implements ControlValueAccessor {

  private _model: any;


  // here goes implementation of ControlValueAccessor

  ...


  addOrRemove(value: any) {

    if (this.contains(value)) {

        this.remove(value);

    } else {

        this.add(value);

    }

  }


  contains(value: any): boolean {

    if (this._model instanceof Array) {

        return this._model.indexOf(value) > -1;

    } else if (!!this._model) {

        return this._model === value;

    }


    return false;

  }


  // implementation for add and remove

  ...

}

复选框组件:


@Component({

selector: 'checkbox',

template: `

  <div (click)="toggleCheck()">

    <input type="checkbox" [checked]="isChecked()" />

    <ng-content></ng-content>

  </div>`

})

export class CheckboxComponent {

  @Input() value: any;


  constructor(@Host() private checkboxGroup: CheckboxGroupComponent) {

  }


  toggleCheck() {

    this.checkboxGroup.addOrRemove(this.value);

  }


  isChecked() {

    return this.checkboxGroup.contains(this.value);

  }

}

子复选框控件引用了组组件(@Host()装饰器)。当复选框被点击toggleCheck()调用addOrRemove()方法组部件上,并且如果复选框的值已经在模型,它被删除,否则,它被添加到模型中。


查看完整回答
反对 回复 2019-12-02
  • 3 回答
  • 0 关注
  • 635 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信