Angular 6 How To Get Values From Multiple Checkboxes and Send in From

左心房为你撑大大i 提交于 2019-12-02 11:04:57

Change your HTML as below.

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

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 changes should be as below.

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

Working Demo

I don't know if this might suit your requirement, but from what I understand all you need to do is change your code to something like this to get an info on which of the checkboxes are actually checked.

Typescript

public form = {
    ...
    interests: {
      blogs: false,
      web: false,
      onlineNews: false,
    },
    ...
  };

HTML

<section class="checkbox-section">
    <mat-checkbox [(ngModel)]="form.interests.blogs">Blogs</mat-checkbox>
    <mat-checkbox [(ngModel)]="form.interests.web">Web</mat-checkbox>
    <mat-checkbox [(ngModel)]="form.interests.onlineNews">Online News</mat-checkbox>
 </section>

I don't know how pushing the value true or false to any array makes any sense or give information on which input is checked.

Stackblitz demo

You can add a change event on each of your mat-checkbox and do the corresponding method to fullify your array:

(The below example could be upgraded using a single method with an other parameter to know which checkbox had a change event)

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

In my example to access the new boolean value you can do like this :

assingValues1(event: MatCheckboxChange) {
var newVal = event.checked;
// your code here
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!