繁体   English   中英

在angular5中签入时如何获取复选框值

[英]How to get checkbox values when checked in angular5

任何人都可以帮忙,我正在尝试在选中复选框时检查名称。 这里我的要求是我不想在 forloop 中显示我的复选框。 我尝试了 oneway,但我觉得这不是正确的方法。 链接如下所示。

https://stackblitz.com/edit/angular-gv2vkj?file=src%2Fapp%2Fapp.component.ts

我在这里尝试的splice 不起作用 任何人都可以请帮助有没有其他最简单的方法。

请不要使用(更改),而是使用“Angular Way”。 那就是:在视图模型中思考。

  <input type="checkbox"  [(ngModel)]="variable"/>

由于你有几个“项目”,你可以使用一个数组,所以你有

  <input type="checkbox"  [(ngModel)]="variable[0]"/>
  <input type="checkbox"  [(ngModel)]="variable[1]"/>

不要忘记在 .ts 中声明

  variable:boolean[]=[];

您的函数“提交”考虑数组并显示值

submit()
{
   let result:string="";
   if (variable[0])
      result+=",Node"
   if (variable[1])
      result+=",Angular"
   ...
   result=result.substr(1);
}

另一种提交方式是

  submit() {
    const values = ['Node', 'Angular', 'Php']
    let result = "";
    values.forEach((x, index) => {
      if (this.variable[index])
        result += "," + x;
    })
    result = result.substr(1);
    console.log(result)
  }

您还可以使用以下功能,该功能是单行的并且非常简单。 只需将目标值传递给您的函数,然后根据它是否已经在数组中添加或删除该值:

<label class="contain">Node
  <input type="checkbox" value="node" (change)="onChange($event.target.value)">
</label>        
<label class="contain">Angular
  <input type="checkbox" value="angular" (change)="onChange($event.target.value)">
</label>
<label class="contain">PHP
  <input type="checkbox" value="php" (change)="onChange($event.target.value)">
  <span class="checkmark"></span>
</label>

然后是onChange函数:

onChange(value) {
  this.Course.includes(value) ? this.Course.splice(this.Course.indexOf(value), 1) 
                                : this.Course.push(value)
}

你只能得到像 true 和 false 这样的检查值。 您可以使用 (change)="onChange($event)" 事件在复选框上触发事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM