Get value from all checked checkbox in angular

后端 未结 3 570
耶瑟儿~
耶瑟儿~ 2021-01-27 16:18

i\'m creating quiz app using angular and i have code like this

  ngOnInit() {
    this.myForm = this.fb.group({
      lessonCode: "test",
      answer:          


        
3条回答
  •  佛祖请我去吃肉
    2021-01-27 16:43

    What you need to do is to add emailCode as FormArray instead of FormControl, this way you will be able to check whether the questionCode already exists, and if yes, you can append to emailCode the option you checked.

    The only things to change are on your onChange method

    First you array variable, you need to add FormArray instead of FormControl

    let array = new FormGroup({
      questionCode: new FormControl(email),
      emailCode: new FormArray([])
    });
    

    Then create a FormControl for your checked option

    let codeOption = new FormControl(code)
    

    And finally, in your if condition, check if the questionCode already exist to just append your formControl to it, or to create a new object.

    if (isChecked) {
      if (emailFormArray.controls.some(obj => obj.get('questionCode').value == email)){
        (emailFormArray.controls.find(obj => obj.get('questionCode').value == email).get('emailCode')).push(codeOption);
      }else{
        (array.get('emailCode')).push(codeOption)
        emailFormArray.push(array)
      }
    }
    

    To be more clear I have modified your stackblitz to fit with your needs

    I have not modified the else condition to remove the options on your FormArray but you just need to copy the if condition to get the index of the code element on your FormArray of emailCode.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题