Привязка таблицы Ng-bootstrap к выбору с помощью Angular8 и Bootstrap4 - PullRequest
1 голос
/ 04 ноября 2019

Я пытался сделать эту работу дольше, чем хотел бы признать. Множество примеров в Stackoverflow, которые близки к тому, что я пытаюсь сделать, но ни один из них, похоже, не отвечает точно на мой вопрос, поэтому я задаю свой вопрос. Я довольно новичок в разработке Angular. Вот что я пытаюсь сделать:

Я пытаюсь отобразить данные в необычной таблице начальной загрузки 4, которая имеет нумерацию страниц, сортировку столбцов и текстовый поиск. Я хочу, чтобы данные, отображаемые в таблице, зависели от того, что выбрано в раскрывающемся списке (в конечном итоге это будет зависеть от 2 раскрывающихся списков, но я упрощаю пример для целей этого вопроса). Эти данные, которые заполняют список выбора и таблицу, должны поступать из службы.

Я создал Stackblitz , чтобы продемонстрировать, что я пытаюсь сделать, но не знаю, как подключитьэто до конца пути. Любая помощь будет принята с благодарностью!

1 Ответ

1 голос
/ 05 ноября 2019

Чтобы это произошло:

  • Каждый раз, когда человек выбирается / изменяется в компоненте персонажа, вам необходимо передать его в компонент таблицы
  • Фильтровать по странамна человека, выбранного и переданного [ недостаточно информации, чтобы сделать это для вас здесь ]
  • используя ваш существующий стек , внесите следующие изменения для реализации первого пункта выше

после изменений person.component.html :

<form>
  <div class="form-group form-inline">
    <select name="person" id="person" (change)='someFunc($event)' [(ngModel)]="selectedOption" >
      <option *ngFor="let user of users" [value]="user.userid" class ="blueText"

      >{{ user.name }}</option>
    </select>
    selected user: {{selectedUser}}
  </div>
</form>

после изменений person.component.ts :

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { PersonService } from './person.service';
import { User } from './user.ts';
import { ChangeAssigneeService } from './change-assignee.service';

@Component({
  selector: 'person',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.scss']
})
export class PersonComponent implements OnInit {

  users: User[];
  selectedUser:any;
 @Output() private personSelected = new EventEmitter<number>();


  constructor(private personService: PersonService, private changeassigneeService: ChangeAssigneeService) { 
    this.selectedUser = '';
  }

  ngOnInit() {
    this.users = this.personService.getAssignees();
  }

someFunc(event){
  this.personSelected.emit(event.target.value);
  this.selectedUser = event.target.value;
}

  changeAssignee(val:any){
    this.changeassigneeService.sendAssignee(val);
    console.log("test");
  }

}

после изменений table-complete.html :

<form>
  <person (personSelected)="onpersonSelected($event)"></person>
  we got <mark>{{personFromChild || 'nothing'}}</mark> from the table component
  <div class="form-group form-inline">
      Full text search: <input class="form-control ml-2" type="text" name="searchTerm" [(ngModel)]="service.searchTerm"/>
      <span class="ml-3" *ngIf="service.loading$ | async">Loading...</span>
  </div>

  <table class="table table-striped">
    <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
      <th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
      <th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let country of countries$ | async">
      <th scope="row">{{ country.id }}</th>
      <td>
        <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2" style="width: 20px">
        <ngb-highlight [result]="country.name" [term]="service.searchTerm"></ngb-highlight>
      </td>
      <td><ngb-highlight [result]="country.area | number" [term]="service.searchTerm"></ngb-highlight></td>
      <td><ngb-highlight [result]="country.population | number" [term]="service.searchTerm"></ngb-highlight></td>
    </tr>
    </tbody>
  </table>

  <div class="d-flex justify-content-between p-2">
    <ngb-pagination
      [collectionSize]="total$ | async" [(page)]="service.page" [pageSize]="service.pageSize">
    </ngb-pagination>

    <select class="custom-select" style="width: auto" name="pageSize" [(ngModel)]="service.pageSize">
      <option [ngValue]="2">2 items per page</option>
      <option [ngValue]="4">4 items per page</option>
      <option [ngValue]="6">6 items per page</option>
    </select>
  </div>

</form>

после изменений table-complete.ts :

import {DecimalPipe} from '@angular/common';
import {Component, QueryList, ViewChildren, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
import { User } from './user.ts';

import {Country} from './country';
import {CountryService} from './country.service';
import {NgbdSortableHeader, SortEvent} from './sortable.directive';
import { ChangeAssigneeService } from './change-assignee.service';


@Component(
    {selector: 'ngbd-table-complete', 
    templateUrl: './table-complete.html', 
    providers: [CountryService, DecimalPipe]})
export class NgbdTableComplete implements OnInit {
  countries$: Observable<Country[]>;
  total$: Observable<number>;
  personFromChild:any;

  //userId$: Observable<string>;
  userId$: string;

  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(public service: CountryService, private changeassigneeService: ChangeAssigneeService) {
    this.countries$ = service.countries$;
    this.total$ = service.total$;
  }

  public onpersonSelected(personPassed: number) {
    this.personFromChild = personPassed;
    /* INSERT the logic to select countries based on this selected value */
  }


  ngOnInit(){
    this.changeassigneeService.changeAssignee$.subscribe(message => {
      this.userId$ = message;
      console.log(message);
    });
  }

  onSort({column, direction}: SortEvent) {
    // resetting other headers
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
      }
    });

    this.service.sortColumn = column;
    this.service.sortDirection = direction;
  }
}
...