获取多个复选框值作为角度数组 [英] get multiple checkbox value as an array in angular

查看:45
本文介绍了获取多个复选框值作为角度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此处的多个复选框中获取值 https://stackblitz.com/edit/angular-ivy-uahtjx 我尝试了这种方法,但对我来说却不适用https://stackblitz.com/edit/quiz-answer-value 我认为这是因为JSON模式不同,第一个是数组,第二个是对象.

i'm trying to get values from multiple checkbox here https://stackblitz.com/edit/angular-ivy-uahtjx i try this approach but didn't with for me https://stackblitz.com/edit/quiz-answer-value i think it's because the JSON schema is different, first one is array, and the second one is object.

我这样设置html

<div *ngFor="let option of form.options">
  <label><input (change)="onChange(i,j, form.code,check.checked)" #check 
  [value]="answers[i].value.forms[j].answer.toString().indexOf(form.code)>=0" formControlName="answer" type="checkbox">{{option}}</label>
</div>

对于这样的更改功能

onChange(indexi: number, indexj: number, code: string, isChecked: boolean) {
  const control = this.answerArray.at(indexi).get("forms")['controls'][indexj].get('answer');
  console.log(control);
}

有人可以帮助我吗?

推荐答案

代码中有几个错误.

您指示的最后一次堆栈闪电(来自 [checked] 和(change),但是 NOT formControlName(这是因为首先是复选框成为已检查").formControl在表单中没有输入.是的,formControl存在,但是没有输入.

The last stackblitz you indicate (that gone from this SO) is an "imaginative" way to mannage a series of check-boxes to feed a formControl that store an array of strings. The idea is that the input has [checked] and (change), but NOT formControlName (it's the reason because at first the check-boxes became "checked"). The formControl has no input in the form. Yes, the formControl exist, but has no input.

复选框的 [checked] 是一个函数,用于指示是否在选项"中添加了选项".包含在控件的值中(使用indexOf)

The [checked] of the check-box is a function that indicate if the "option" is include in the value of the control (using indexOf)

(change)具有作为参数的索引,以本地化formControl,即"option"的值.以及是否检查.

The (change) has as arguments, the indexes -to localize the formControl-, the value of the "option" and if is checked or not.

A 更简单的Stackblitz 展示这个概念:

<!--see that "answer" has no input, it's only a variable in .ts-->
<div *ngFor="let option of options">
<input #check type="checkbox"
  [checked]="answer.indexOf(option)>=0"
  (change)="onChange(option,check.checked)"
>
{{option}}
</div>

  answer=["check 2"]
  options=["check 1","check 2","check3"]
  onChange(option:string,checked:boolean)
  {
     if (checked && this.answer.indexOf(option)<0)
         this.answer=[...this.answer,option]
         .sort((a,b)=>this.options.indexOf(a)>this.options.indexOf(b)?1:-1)
    if (!checked)
          this.answer=this.answer.filter(x=>x!=option)
  }

好吧,在您的代码中

1.-更改表格(请参阅代码中的注释)

1.-Change the form (please, see the comments in the code)

    <div *ngIf="form.type == 'checkbox'">
        <p>{{form.title}}</p>
        <div *ngFor="let option of form.options">
           <!--in your code WRONG (change)="onChange(i,j, form.code,check.checked)" -->
           <!-- see that we need send the "option", not the form.code-->
            <label><input #check (change)="onChange(i,j, option,check.checked)"
           <!--use checked, not value, and remove the "toString"-->
             [checked]="answers[i].value.forms[j].answer.indexOf(option)>=0"
              <!--see that we has no formControlName="answer" -->
              type="checkbox">{{option}}</label>
        </div>
    </div>

onChange函数,只需在checked = true时添加"code"即可.并且如果checked = false,则删除代码".好吧,有一个难题是排序"的.回应.为了对响应进行排序,我们比较选项"中的indexOf值.

The function onChange, it's simply if checked=true add the "code" and if checked=false remove the "code". Well, there are a dificult that is "sort" the responses. For sort the response, we compare the indexOf the value in the "options"

我使用辅助变量选项"获得选项"

I use an auxiliar variable "options" to get the "options"

2.-将功能更改为onChange by

2.-Change your function onChange by

  onChange(indexi: number, indexj: number, code: string, isChecked: boolean) {
    const control = this.answerArray.at(indexi).get("forms")["controls"][indexj]
      .controls.answer;
    
    const options=this.listFormField[indexi].sectionItems[indexj].options
    //options will be, eg. ["check 1","check 2","check 3"]
    if (isChecked && control.value.indexOf(code) < 0)
      control.setValue(
        [...control.value, code].sort((a: string, b: string) =>
          options.indexOf(a) >options.indexOf(b)
            ? 1
            : -1
        )
      );

    if (!isChecked && control.value.indexOf(code) >= 0)
      control.setValue(control.value.filter(x => x != code));
  }

注意:您需要修改代码,实际上,当您创建表单时,所有的答案"是数组(只需将它们作为复选框的答案的答案"数组即可)

NOTE: You need revised the code, Actually, when you create the form, all yours "answers" are arrays (only need to be array the "answer" that they are ansers of a check-boxs)

已更新为避免错误(如果答案为空),我们可以或避免在创建表单或其他选项时将选中的代码更改为

Updated To avoid errors if answer is null, we can or avoid when create the form or, another option, change the code in checked as

[checked]="(answers[i].value.forms[j].answer || []).indexOf(option)>=0"

对于路径值,如果仅是一个元素,例如

To path value we can, if only is an element, e.g.

const i=0
const j=1
this.response.get('answers.'+i+'.forms.'+j+'.answer')
     .patchValue(["check 1","check 2"])

是的,要获得答案"我们可以使用获取"使用索引.理解这一点是因为,当我们使用formGroup的formArray时,我们编写 [formGroupName] ="i" .如果要在FormGroup上创建pathValue,则需要考虑到,如果在数组上创建pathValue,则pathValue不会将元素添加到formArray,因此,如果我们发送更多的元素,则不会添加该元素.此外,如果我们发送的元素pathValue较少,则删除这些元素

Yes, to get an "answer" we can use "get" using the index. Perhafs this makes understand because when we use a formArray of formGroup, we write [formGroupName]="i". If we want to make a pathValue over a FormGroup, we need take account, that if we make pathValue over an array, pathValue NOT add elements to the formArray, so if we send more elements, this it's not added. futhermore, if we send less elements, pathValue, remove the elements

考虑到这一点,我们也可以做到,例如

take account this, we can also make,e.g.

this.response.get('answers.'+i+'.forms')
     .patchValue(
        [
          {answer:"radio 2"},
          {answer:["check 1","check 2"]},
          {answer:"text input"},
          {answer:"text area"},
          {answer:["check 6"]},
         ]
        )  

这篇关于获取多个复选框值作为角度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆