如何在Angular中接受多个选中的复选框?

时间:2018-09-07 11:17:12

标签: angular checkbox

我有多个已选中的复选框(ngOninit)。现在我编辑此选中的复选框,有时我不进行编辑,但我保存了复选框,这使this.checklist为空,但是这里有一些复选框已选中,所以当我不编辑复选框时到时候,应该了解如何将默认的已选中复选框放入this.checkedlist或任何其他解决方案了。

<label *ngFor="let statusCategoryObj of statusCategoryObj">
 <mat-checkbox value="{{statusCategoryObj.categorytitle}}" name="categories"
   [checked]="checkedCategories(statusCategoryObj.id)" (change)="onCheckboxChange(statusCategoryObj,$event)">
    {{statusCategoryObj.categorytitle}}</mat-checkbox>
</label>
<button mat-raised-button (click)="updateStatusDetailsById({'id':this.editStatusObj.id})">SAVE</button>

edit-status.component.ts

ngOnInit(){
  this.statusService.editStatusDetailsById({'id': id}).subscribe(
    (data) => {
      if(data.status == 28){
        this.editStatusObj.id = data.payload[0].id;
        this.editStatusObj.categories = data.payload[0].categories;
        this.allCategories = this.editStatusObj.categories.split(',');
      }        
    }
  )
}

checkedCategories(id){
  for(var i = 0 ; i < this.allCategories.length; i++){
    if(id == this.allCategories[i]){
      return true;
    }
  }  
  return false;
}

onCheckboxChange(statusCategoryObj, event) {
  if(event.checked) {
    this.checkedList.push(statusCategoryObj.id);
  }else{
    for(var i=0 ; i < this.statusCategoryObj.length; i++) {
     if(this.checkedList[i] == statusCategoryObj.id){
       this.checkedList.splice(i,1);
     }
    }
  }
}

updateStatusDetailsById(id){
  const formData = new FormData();
  formData.append('categories',this.checkedList.toString());
  this.statusService.updateStatusDetailsById(formData).subscribe(
    (data) => {
      if(data.status == 29){
        console.log(data.payload);
      }  
    }
  )
} 

1 个答案:

答案 0 :(得分:3)

您要尝试执行的操作是保留复选框列表并设置默认复选框值。

在下面的代码中,它将假定您从某个地方加载了默认值,然后在ngOnInit函数中为您自动检查了默认值

import { Component, OnInit } from '@angular/core'; 

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  form: FormGroup;
  notifications:Array<{name:string, checked:boolean}> = ['Post', 'Email', 'SMS', 'Pick Up', 'Other'].map(item => ({name: item, checked: false}))
  loadedNotifications = ['Post', 'Email']


  constructor() {
  }

  ngOnInit() {
    // assumed loadedNotifications came from an asynchronous process
    this.loadedNotifications.forEach(loaded => {
      const notification = this.notifications.find(item=> item.name === loaded)
      if(notification){ 
        notification.checked = true
      }
    })
  }

  submit() {
    const param = this.notifications.filter(item => item.checked).map(item => item.name)
    console.log('param', param)
  }
}

模板文件是这样的,请观察(change)函数,在其中切换每个项目的选中字段

<form (ngSubmit)="submit()" novalidate>

    <div>
        <p>Kindly indicate how you would want your </p>
        <p>Notification of transfer to be dispatched</p>
        <p>to you: </p>
    </div>
    <ul>
        <li *ngFor="let item of notifications">
            <label>{{item.name}}</label>
            <input type='checkbox' (change)="item.checked = !item.checked" [checked]="item.checked" />
        </li>
    </ul>


    <button type="submit">
        Send
      </button>
</form>

这是正在运行的代码:https://stackblitz.com/edit/angular-pv3pyk