2017-06-10 36 views
1

在一個div中,我填充了所需的複選框。將選中的複選框從一個div移動到另一個div。如果取消選擇其他div,它應該反映在最初的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

+0

問題是什麼?而且你有什麼確切的想法有點不清楚。你是否想在其他div中使用複選框?你能否解釋一下這個用例,因爲我很難理解這是什麼。 – Alex

+0

@ AJT_82請參閱編輯先生。 –

+0

基本上我想知道選中的複選框是否可以使用ngModel顯示在上面的框中,以便檢查/取消選中事件相互影響。 –

回答

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

盒子獲取的未選中,因爲我們加入以下我們新prope線和第一陣列(所有用戶) rty checked

[checked]="usersbysite.checked" 

DEMO

+0

@ AJ_82非常感謝您先生...明白了。 –

+0

非常歡迎你,很高興我能幫到你!祝你有美好的一天,快樂的編碼! :) – Alex

相關問題