Angular 6如何从多个复选框获取值并从中发送 [英] Angular 6 How To Get Values From Multiple Checkboxes and Send in From

查看:217
本文介绍了Angular 6如何从多个复选框获取值并从中发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的表单中使用mat-checkbox作为输入,但是在文档上找不到与之相关的任何东西.

I'm trying to use mat-checkboxes as input in my form, but can't really find anything on docs regarding it.

HTML

<section class="checkbox-section">
 <mat-checkbox [(ngModel)]="bChecked">Blogs</mat-checkbox>
 <mat-checkbox [(ngModel)]="wChecked">Web</mat-checkbox>
 <mat-checkbox [(ngModel)]="oChecked">Online News</mat-checkbox>
 </section>

打字稿

    public form = {
    name: null,
    email: null,
    birthday: null,
    company: null,
    interests: [],
    newsletter: null,
    address: null,
    password: null,
    password_confirmation: null,
  };

我正在尝试获取静态复选框的值,然后将其推送到兴趣数组

I'm trying to get the values of the checkboxes which are static and then push to my interests array

推荐答案

如下更改您的 HTML .

<section class="checkbox-section">
  <mat-checkbox [(ngModel)]="bChecked" (change)="onCheckboxChagen($event, 'Blogs')">Blogs</mat-checkbox>
  <mat-checkbox [(ngModel)]="wChecked" (change)="onCheckboxChagen($event, 'Web')">Web</mat-checkbox>
  <mat-checkbox [(ngModel)]="oChecked" (change)="onCheckboxChagen($event, 'Online News')">Online News</mat-checkbox>
  </section>

由于需要使用静态标签作为复选框的值,因此可以将静态标签作为第二个参数传递给onCheckboxChagen方法.根据复选框的值,您可以从interests数组中pushpop元素.

As you need to use static label for checkbox value, you can pass a static label as the second argument to the onCheckboxChagen method. According to the value of the checkbox you can push and pop elements from the interests array.

TS 的更改应如下所示.

  onCheckboxChagen(event, value) {

    if (event.checked) {

      this.interests.push(value);
    } 
    if (!event.checked) {

      let index = this.interests.indexOf(value);

      if (index > -1) {

        this.interests.splice(index, 1);
      }
    }
  }

工作演示

这篇关于Angular 6如何从多个复选框获取值并从中发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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