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

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

问题描述

我正在尝试在表单中使用 mat-checkboxes 作为输入,但在文档中找不到任何关于它的内容.

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