Реализация таблицы с фильтрацией и разбиением на страницы с использованием ng-bootstrap - PullRequest
0 голосов
/ 22 июня 2019

Я делаю веб-приложение, используя Angular и ng-bootstrap.Я следую документации из ng-bootstrap , чтобы создать таблицу с Filtering и Pagination .Я видел решения, но все они включают в себя сортировку, а код длиннее, сложнее, и в моем случае сортировка мне не нужна.

Сейчас фильтрация работает хорошо, но разбиение на страницы не работает«т.По крайней мере, количество кнопок разбивки на страницы меняется, хотя они не работают.

шаблон:

<table class="table table-striped">
    <thead class="thead-dark">
    <tr>
      <th scope="col">Localization</th>
      <th scope="col">Position</th>
      <th scope="col">Company</th>
      <th scope="col">Created at</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let job of searchedJobs$ | async">
      <td scope="row"><ngb-highlight [result]="job.location" [term]="filter.value"></ngb-highlight></td>
      <td><ngb-highlight [result]="job.position" [term]="filter.value"></ngb-highlight></td>
      <td><ngb-highlight [result]="job.company" [term]="filter.value"></ngb-highlight></td>
      <td>{{job.createdAt.toDate() | date: 'mediumDate'}}</td>
    </tr>
    </tbody>
  </table>

  <div class="d-flex justify-content-between p-2">
    <h6>{{jobs.length}} {{jobs.length > 1 ? 'jobs' : 'job'}} in this category</h6>

    <ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [pageSize]="pageSize">
    </ngb-pagination>
  </div>

класс:

export class CategoryListComponent implements OnInit {
  // Original array
  jobs: JobId[];

  // Pagination
  page = 1;
  pageSize = 20;
  collectionSize = 0;

  // Filtered array
  searchedJobs$: Observable<JobId[]>;

  // Value received from service to filter the array
  filter = new FormControl('');

  constructor(
    private jobService: JobService,
    private searchService: SearchService
  ) {

    // This is for filtering
    this.searchedJobs$ = this.filter.valueChanges.pipe(
      startWith(''),
      map(text => this.search(text))
    );
  }

  ngOnInit() {
    // Receives an array of jobs
    const subJobs = this.jobService.getAll().subscribe(res => {
      this.jobs = res;
      // Updates the collectionSize
      this.collectionSize = this.jobs.length;
    });

    // This is for filtering. I receives a value from a component using a service as intermediary
    this.searchService.currentMessage.subscribe(message => {
      this.filter.setValue(message);
    });
  }

  // This is for filtering
  search(text: string): JobId[] {
    const array = this.jobs
      .filter(job => {
        return job.location.toLowerCase().includes(text.toLowerCase())
          || job.position.toLowerCase().includes(text.toLowerCase())
          || job.company.toLowerCase().includes(text.toLowerCase());
      });

    // Updates the collectionSize
    this.collectionSize = array.length;

    return array;
  }

  // I don't know how/where to implement this method
  get jobsFiltered(): JobId[] {
    return this.jobs
      .slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
  }
}

Не знаюЯ не знаю, является ли это лучшим / самым простым кодом из когда-либо существовавших.

Моя цель - работать с фильтрацией и разбивкой на страницы таблицы.Уметь правильно фильтровать и использовать кнопки нумерации страниц, чтобы увидеть больше результатов.

...