Angular开发(二十二)-angular处理复选框选值的问题

在angular开发中单选框可以获取到值,但是复选框传统的方式获取的值是truefalse,但是实际开发中往往需要获取到值或者是id

一、在响应式表单与表单校验基础上扩展

<div class="form-group">
    <label>性别:label>
    <div class="radio">
        <label class="radio-inline" *ngFor="let item of sex">
            <input type="radio" formControlName="sex" [value]="item"/>{{item}} 
        label>
    div>
div>
<div class="form-group">
    <label>兴趣爱好:label>
    <div class="checkbox">
        <label *ngFor="let item of hobbyList" class="checkbox-inline">
            <input type="checkbox" (click)="selectCheckbox($event.target.checked,item)"/>
            {{item}}label>
    div>
div>
private hobbyList:Array = ["篮球","足球","羽毛球"];
private sex:Array = ["男","女"];
private selectHobby:Array = [];
...
//定义一个复选框的选中方法
selectCheckbox(check:boolean,value:string){
  //先判断选中的数组里面是否包括当前值,includes目前不支持
  //var isInclude:boolean = this.selectHobby.includes(value); 
  var index:number = this.selectHobby.indexOf(value);
  //当前选择的就追加否则就移除
  if(check){
    if(index < 0){
      this.selectHobby.push(value);
    }
  }else{
    if(index > -1){
      this.selectHobby = this.selectHobby.filter((ele,index)=>{
        return ele != value;
      })
    }
  }
  this.myform.value["hobby"] = this.selectHobby.toString();
}

你可能感兴趣的:(angular2)