【问题标题】:Move selected checkboxes from one div to another. If unselect from the other div, it should reflect in the initial div将选中的复选框从一个 div 移动到另一个。如果从其他 div 中取消选择,它应该反映在初始 div
【发布时间】:2017-06-12 23:24:28
【问题描述】:

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

我还设法将选中的复选框存储到一个对象中。

我想知道如何在另一个 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 的对象 .

更新: 在下面显示的图像中,我已经填充了复选框。当我单击任何这些复选框时,它应该转到上面的框。此外,当我从上面的框中取消选中时,它应该从上面的框中删除,并且它在下面的框中的相应值也应该被取消选中。

【问题讨论】:

  • 有什么问题?而且有点不清楚你到底想要什么。你想在另一个 div 中也有复选框吗?您能否解释一下这个用例,因为我无法理解它的用途。
  • @AJT_82 请看编辑先生。
  • 基本上我想知道是否可以使用ngModel将选中的复选框显示在上框上,以便检查/取消选中事件相互影响。
  • 好的,现在我想我明白你想要什么了! :) 稍后我一定会看看你的代码。刚才我遇到了另一个编码问题:)

标签: angular checkbox


【解决方案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

【讨论】:

  • @AJ_82 非常感谢先生...知道了。
  • 非常欢迎您,很高兴我能帮上忙!祝你有美好的一天,快乐的编码! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 2017-09-19
  • 1970-01-01
相关资源
最近更新 更多