【问题标题】:How do I send values of selected checkbox as an array to the function?如何将选定复选框的值作为数组发送到函数?
【发布时间】:2019-09-02 08:06:13
【问题描述】:

我对使用 Angular 还很陌生,想知道是否有一种简单的方法可以首先检查复选框是否被选中。如果它被选中,我想将它传递给saveOptions 函数。如果选择了多个,我想将它们全部传递并保存到一组选项中。有人可以帮帮我吗?

import { Component } from '@angular/core';
import { forEach } from '@angular/router/src/utils/collection';
import { Options } from 'selenium-webdriver/ie';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  options: any = []



  saveOptions(x:any[]){
     x.forEach(element => {
      this.options.push(element);
    });
  }

} 
<ul class="option-row">
    <div class="option-group">
        <li><input type="checkbox"  id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
        <li><input type="checkbox"  id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
        <li><input type="checkbox"  id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
    </div>
    <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
    <button type="button" (click)="saveOptions();">Submit</button>
</ul>

【问题讨论】:

  • 你可以看到这个答案。它会对你更好。 Click here

标签: html angular typescript


【解决方案1】:

您可以借助 div 元素的 ngFor[value] 以动态方式进行此操作。

为您的li 元素使用一个数组,修改您的模板和组件,如下所示。

Component.html

 <ul class="option-row">
    <div *ngFor="let li of listedValue" class="option-group">
        <li><input type="checkbox"  id="option-{{li}}" [value]="l" required (click)="setCheckbox($event,li)"> <label for="option-{{li}}">Option 1</label></li>
    </div>
        <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
        <button type="button" (click)="saveOptions();">Submit</button>
</ul>

Component.ts

name = 'Angular 5';
  listedValue: any = [1, 2, 3];
  options: any = []

  setCheckbox(event: any,value: any) {
     if (event.target.checked)
       this.options.push(value)
     else
       this.options= this.options.filter(val => val != value);
  }

  saveOptions() {
   console.log(this.options);
  }

我为您的情况创建了一个stackblitz,请检查一次。我希望这能解决你的问题:)

【讨论】:

  • 这将在选中和取消选中时不断添加到数组中。
  • 不要混淆stackarray,js在任何数组上都提供栈函数。 pop 仅删除顶部元素,因此检查和取消检查时输出会有所不同,并且它们对突变不友好。
【解决方案2】:

我认为你可以使用表单控制响应式表单它会帮助你

【讨论】:

    【解决方案3】:

    一种方法是订阅表单的 valueChanges,如下所示:

    export class AppComponent implements OnInit {
      options: any = []
      model = { optionOne: false, optionTwo: false, optionThree: false }
      formChangesSubscription;
      @ViewChild('form') ngForm: NgForm;
    
      ngOnInit() {
        this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
          console.log(x);
        })
      }
    
      saveOptions(x: any[]) {
        x.forEach(element => {
          this.options.push(element);
        });
      }
    } 
    
    <form #form="ngForm">
        <ul class="option-row">
            <div class="option-group">
                <li><input type="checkbox" [(ngModel)]="model.optionOne" name="optionOne" id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
          <li><input type="checkbox" [(ngModel)]="model.optionTwo" name="optionTwo" id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
          <li><input type="checkbox" [(ngModel)]="model.optionThree" name="optionThree" id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
        </div>
        <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
        <button type="button" (click)="saveOptions();">Submit</button>
    </ul>
    </form>
    

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

    【讨论】:

      【解决方案4】:

      我只是在这里扩展 ganesh 的答案!

      Component.html

      <form #form="ngForm">
           <ul class="option-row">
          <div *ngFor="let li of listedValue; index as i" class="option-group">
              <li><input type="checkbox"  id="option-{{li}}" [value]="l" required (click)="setCheckbox(li, i)"> <label for="option-{{li}}">Option {{ i }}</label></li>
          </div>
              button type="button" (click)="saveOptions();">Submit</button>
      </ul>
      </form>
      

      component.ts

      name = 'Angular 5';
        listedValue: any = [0, 1, 2];
        options: any = []
      
        ngOnInit(){}
      
        setCheckbox(event: any, index: number) {
          if(!this.options.includes(event)){
            this.options = [...this.options, event];
          }else {
            this.options = this.options.filter((item) => item !== event);
          }
        }
      
        saveOptions() {
         console.log(this.options);
        }
      

      StackBlitz

      【讨论】:

        猜你喜欢
        • 2013-08-13
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-27
        • 1970-01-01
        • 2014-01-15
        • 1970-01-01
        相关资源
        最近更新 更多