Angular 6の使用:
データを含むHTMLテーブルがあり、行の1つはチェックボックスで、ユーザーは個々の行を選択するか、ヘッダーの[すべてのチェックボックスを選択]を使用してすべての行を選択できます。
<table class="table table-hover table-responsive table-striped">
<thead>
<tr>
<th>
<a>
<input type="checkbox" [(ngModel)]="masterSelected" name="list_name" value="m1" (change)="checkUncheckAll()" />
</a>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of data">
<td>
<input type="checkbox" [(ngModel)]="c.isSelected" value="{{c.name}}" (change)="isAllSelected()">
</td>
<td>other td data goes below</td>
</tr>
</tbody>
</table>
Below is my Angular component code:
export class GridComponent implements OnChanges {
@Input() data: any[] = [];
allSelectedData: any[]=[];
checkUncheckAll() {
for (let i = 0; i < this.data.length; i++) {
this.data[i].isSelected = this.masterSelected;
}
this.getCheckedItemList();
}
isAllSelected() {
this.masterSelected = this.data.every(function (item: any) {
return item.isSelected === true;
});
this.getCheckedItemList();
}
//Method called when checbox is checked and to update the array
getCheckedItemList() {
this.checkedList = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].isSelected) {
this.allSelectedData.push(this.data[i]);
}
}
//Calling my service observable to store the data which other components can subscribe to
this.myService.setSelectedData(this.allSelectedData);
}
}
上記の関連コードを投稿するだけです。
ユーザーがチェックボックスをクリックするか、すべての行を選択して1つの行を選択すると、this.allSelectedDataを使用して選択したデータを保持します。
ここではすべてが正常に機能します。この問題は、ユーザーが選択した値のチェックを外すと発生します。this.allSelectedDataからその値を削除する方法がわかりません。
すべてをもう一度ループして個々の値を確認する必要がありますか、それとももっと良い方法があるかどうかを確認する必要がありますか。
私が探しているのは、this.allSelectedDataがすべての選択を保持する必要があるということです。誰かが新しい行をチェックしてからこれに追加し、誰かが行のチェックを外した場合はこれを更新してそのエントリを削除します。
ありがとう
これを試してください。これは、ユーザーがフロントエンドから選択した行です。
singleSelecttion(row){
this.selectAllItems=false;
row.isSelected =! row.isSelected;
if(row.isSelected ==true){
var index = this.selectedRowArr.map(function(item){
return item.Id;
}).indexOf(row.Id);
if(index== -1){
this.selectedRowArr.push(row);
}
}
else if(row.isSelected ==false){
var index = this.selectedRowArr.map(function(item){
return item.Id;
}).indexOf(row.Id);
if(index != -1){
this.selectedRowArr.splice(index,1);
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加