将所选复选框从一个div移动到另一个div。如果从其他div中取消选择,它应该反映在初始div中

时间:2017-06-10 07:14:29

标签: angular checkbox

在一个div中,我填写了所需的复选框。

此外,我已设法将所选复选框存储到对象。

enter image description here

我想知道如何在另一个div中显示这个对象(复选框)。此外,如果我从其他div中取消选择它也应该反映在初始div(双向绑定)。 以下代码用于填充所选复选框。

selectedUsers(usrbysite: any, event: any) { //getting values of selected check boxes
    var index = this.checkeduserslist.indexOf(usrbysite);
    if (event.target.checked) {
        if (index === -1) {
            this.checkeduserslist.push(usrbysite);
            console.log('added', usrbysite);
        }
    }
    else {
        if (index !== -1) {
            this.checkeduserslist.splice(index, 1);
            console.log('removed', usrbysite);
        }
    }
    console.log('CHECKEDUSERSLIST :', this.checkeduserslist);
}

以下代码是最初填充的div:

<div style="width:100%; height:120px; overflow-x: auto;">
<div *ngFor="let usersbysite of usersbysite" style="display:inline">
      <input type="checkbox"
          name="usersbysite"
          value="usersbysite.user"
          (change)="selectedUsers(usersbysite, $event)" />
           {{usersbysite.username}}
</div></div>

我想在另一个div中填充名为 selecteduserlist 的对象  

更新: 在下面显示的图像中,我填充了复选框。当我点击这些复选框中的任何一个时,它应该转到上面的框中。此外,当我取消选中上面的框时,它应该从上面的框中删除,并且还应取消选中下面框中的相应值。 enter image description here

1 个答案:

答案 0 :(得分:1)

我会向你的阵列介绍一个新属性......让我们称之为checked。这会让您的生活更轻松。你可以在获得阵列时创建它,或者你可以像我们这里一样随时添加它。所以,像你一样填充阵列看起来对我来说很好,所以我根本不会触摸它。

另一个数组显示如下,我们将所有复选框都选为默认选项:

<div *ngFor="let usr of checkeduserslist" style="display:inline">
  <input type="checkbox" (change)="remove(usr)" [checked]="true"/> {{usr.username}}
</div>

然后,更改事件将从阵列中删除该用户,并取消选中其他阵列中的复选框:

remove(user) {
  let index = this.checkeduserslist.indexOf(user);
  this.checkeduserslist.splice(index, 1);
  // find the unchecked user from other array and uncheck the checkbox
  let resetUser = this.usersbysite.find(x => x.userid == user.userid)
  resetUser.checked = false;
}

未选中该框,因为我们使用新属性checked向第一个数组(包含所有用户)添加了以下行。

[checked]="usersbysite.checked"

<强> DEMO