我正在尝试通过角度表单生成器发送多个复选框,但无法正常工作

时间:2018-07-18 10:28:42

标签: angular forms formbuilder

当我运行此代码时,复选框在前端不可见。我想做的是从用户那里获取复选框的多个输入,并将其发送到api。请为此提供帮助。

 <form [formGroup]="form" (submit)="submit(form.value)">
        <div *ngFor="let addon of addOns; let i = index">
                <input type="checkbox" [formControl] ="addOn">
                {{user.addOns[i].name}}
        </div>
        <button type="submit">
                Calculate Premium
        </button>
    </form>
    {{ form.value | json }}

这是数据未与表单控件名称绑定的组件类-有谁能告诉我即时通讯在做什么

     export class FourWheelerComponent implements OnInit {

  user ={
    addOns:[
      {name:'IsValidDrivingLicense', selected:true, id:1},
      {name:'IsMoreThanOneVehicle', selected:false, id:2},
      {name:'IsNoPrevInsurance', selected:false, id:3},
      {name:'IsTransferOfNCB', selected:false, id:4}
    ]
  }
  form;

  constructor(private fb: FormBuilder,
  private _quoteService: QuoteService) { 
    console.clear();

    this.form = this.fb.group({
      addOns:this.buildAddOns()
    });
    console.log(this.form.get("addOns"))
  }



  ngOnInit() {


  }
  getAddOns(): FormArray{
    return this.form.get('addOns') as FormArray;
  };

  buildAddOns(){
    const arr = this.user.addOns.map(s=>{
      return this.fb.control(s.selected,);
    })
    return this.fb.array(arr);
  }


  submit(value){
    const f = Object.assign({}, value, {
      addOns: value.addOns.map((s,i) =>{
        return{
          name: this.user.addOns[i].name,
          selected:s,

        }
      })
    });
    console.log(f);
  }

}

1 个答案:

答案 0 :(得分:1)

问题出在您写的getAddOns()的get函数中,它应该是get addOns(),因为它是getter函数,在创建表单组时正在使用该函数,在{{ 1}}我已经尝试过检查代码,  您可以查看https://stackblitz.com/edit/angular-forms-checkbox上的内容。