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

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

问题描述

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

我这样设置我的html

<label><input (change)=onChange(i,j, form.code,check.checked)";#查看[value]=answers[i].value.forms[j].answer.toString().indexOf(form.code)>=0";formControlName="答案";type="checkbox">{{option}}</label>

对于我这样的更改功能

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

有人可以帮我吗?

解决方案

您的代码中存在多个错误.

您指出的最后一次堆栈闪电战(来自 这个 SO) 是一个富有想象力的"管理一系列复选框以提供存储字符串数组的 formControl 的方法.这个想法是输入有 [checked](change),但 NOT formControlName(这是因为起初复选框变为已检查").formControl 在表单中没有输入.是的,formControl 存在,但没有输入.

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

(change) 作为参数,索引 - 本地化 formControl -,选项"的值;以及是否检查.

一个更简单的stackblitz 展示这个概念:

<div *ngFor=让选项的选项"><input #check type="checkbox";[选中]=answer.indexOf(option)>=0";(change)="onChange(option,check.checked)";>{{选项}}

answer=[检查2"]选项=[检查1",检查2",检查3"]onChange(option:string,checked:boolean){如果(选中&& this.answer.indexOf(option)<0)this.answer=[...this.answer,option].sort((a,b)=>this.options.indexOf(a)>this.options.indexOf(b)?1:-1)如果(!检查)this.answer=this.answer.filter(x=>x!=option)}

好吧,在你的代码中

1.-更改表单(请查看代码中的注释)

 

<p>{{form.title}}</p><div *ngFor="let option of form.options"><!--在你的代码中 WRONG (change)=onChange(i,j, form.code,check.checked)";--><!-- 请注意,我们需要发送选项",而不是 form.code--><label><input #check (change)=onChange(i,j, option,check.checked)";<!--使用已检查,而不是值,并删除toString"-->[选中]=answers[i].value.forms[j].answer.indexOf(option)>=0";<!--看我们没有 formControlName="answer";-->type="checkbox">{{option}}</label>

函数onChange,只要checked=true 添加代码"即可如果检查=假删除代码".嗯,有一个困难是排序".响应.为了对响应进行排序,我们比较选项"中的 indexOf 值

我使用辅助变量选项";获取选项"

2.-更改您的函数 onChange

 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//选项将是,例如.[检查1",检查2",检查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));}

注意:您需要修改代码,实际上,当您创建表单时,您所有的答案"都将被删除.是数组(只需要排列答案",它们是复选框的分析者)

更新 为避免在 answer 为 null 时出错,我们可以或避免在创建表单时,或者,另一种选择,将代码更改为 check as

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

对于路径值我们可以,如果只是一个元素,例如

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

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

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

this.response.get('answers.'+i+'.forms').patchValue([{答案:收音机 2"},{answer:["check 1","check 2"]},{答案:文本输入"},{答案:文本区域"},{答案:[检查6"]},])

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.

i set up my html like this

<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>

and for my change function like this

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

can someone help me?

解决方案

Thre're several errors in your code.

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.

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

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

A more simple stackblitz to show this concept:

<!--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)
  }

Well, in your code

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>

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.-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"])

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天全站免登陆