I have encountered an issue with my checkbox. When I navigate to the next page in server-side pagination and then return, the checkbox becomes unchecked.
I need to extend the object to include the checked field. How can I accomplish this?
Currently, the object is retrieved from the server using http.get.
If the Items objects include a checked field, I can utilize a new method that automatically checks the checkbox when returning to the site.
HttpService:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Items } from './items';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class HttpService {
constructor(private http: HttpClient) {}
private url: string = 'url-link';
getItems(page: number, pageSize: number): Observable<Items> {
const start = (page - 1) * pageSize;
return this.http.get<Items>(`${this.url}/${start}/${pageSize}`);
}
}
app.component.ts :
import { Component, OnInit } from '@angular/core';
import { HttpService } from './http.service';
import { Items } from './items';
import { List } from './list';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
private items = new Items();
private checkItem: List[] = [];
private pageSize: number = 10;
private p: number = 1;
constructor(private httpService: HttpService) { }
ngOnInit(): void {
this.getItems(1, this.pageSize);
}
private getItems(event: number, pageSize: number) {
pageSize = this.pageSize;
this.p = event;
this.httpService.getItems(event, pageSize).subscribe(items => this.items = items);
}
private getItemFromCheckbox(item: List, event) {
const index = this.checkItem.findIndex(newItem => newItem.id === item.id);
if(event.target.checked) {
if(index === -1) {
this.checkItem.push(item);
}
}
else {
if(index !== -1) {
this.checkItem.splice(index, 1);
}
}
console.log(this.checkItem);
}
private sortItems(sortBy: string) {
this.items.list.sort((a: List, b: List) => {
if (sortBy === 'id-up') {
if (a.id < b.id) {
return -1;
}
else if (a.id > b.id) {
return 1;
}
}
else if (sortBy === 'id-down') {
if (a.id < b.id) {
return 1;
}
else if (a.id > b.id) {
return -1;
}
}
// Repeat for other fields like name, type, version
});
}
}
app.component.html :
<tr *ngFor="let item of items.list | paginate : { id: 'server', itemsPerPage: pageSize, currentPage: p, totalItems: items.count }; let i = index">
<th><input class="form-check" type="checkbox" id="checkbox_category_{{i}}" (change)="getItemFromCheckbox(item, $event)" mdbDeepDirective></th>
<th scope="row">{{item.id}}</th>
<td>{{item.name}}</td>
<td>{{item.type}}</td>
<td>{{item.version}}</td>
</tr>