Не удается отфильтровать в таблице PrimgNg (Angular, primeNg) - PullRequest
0 голосов
/ 27 марта 2020

Я на самом деле пытаюсь отфильтровать через инстансы, я сделал следующий код: В моем component.ts у меня есть это:

import { Component, OnInit } from "@angular/core";
import { AlertingService } from "src/app/services/alerting.service";
import { AlertingDB } from "src/app/models/alerting-db";
import { DatePipe } from "@angular/common";
import { MessageService } from "primeng/api";

@Component({
  selector: "app-alerts-history",
  templateUrl: "./alerts-history.component.html",
  styleUrls: ["./alerts-history.component.css"]
})
export class AlertsHistoryComponent implements OnInit {
  AlertsHistory: AlertingDB;
  cols: string[];

  constructor(
    private alertingService: AlertingService,
    public datepipe: DatePipe,
    private messageService: MessageService
  ) {
    this.cols = [
      "Name",
      "Instance",
      "Severity",
      "Summary",
      "State",
      "Active Date"
    ];
  }

  ngOnInit() {
    this.alertingService.getAllAlertsFromDB().subscribe(res => {
      this.AlertsHistory = res;
    });
  }

  deleteHistory() {
    this.alertingService.deleteAllAlertsFromDB().subscribe(async result => {
      this.messageService.add({
        severity: "info",
        summary: "Success",
        detail: `History Cleared`,
        sticky: true
      });
      this.AlertsHistory = await this.alertingService
        .getAllAlertsFromDB()
        .toPromise();
    });
  }
}

В моем компоненте. HTML файл У меня есть это:

<button
  pButton
  type="button"
  label="Clear History"
  class="ui-button-danger"
  style="margin-bottom: 15px;margin-top: 15px;"
  (click)="deleteHistory()"
></button>
<div>
  <p-table
    autoLayout="true"
    ng-style="overflow: auto;"
    #dt
    [columns]="cols"
    [value]="AlertsHistory"
    [paginator]="true"
    [rows]="15"
  >
    <ng-template pTemplate="header" let-columns>
      <tr>
        <th *ngFor="let col of columns" [pSortableColumn]="col">
          {{ col }}
          <p-sortIcon
            [field]="col"
            ariaLabel="Activate to sort"
            ariaLabelDesc="Activate to sort in descending order"
            ariaLabelAsc="Activate to sort in ascending order"
          >
          </p-sortIcon>
        </th>
      </tr>
      <tr>
        <th *ngFor="let col of columns" [ngSwitch]="col">
          <input
            *ngSwitchCase="'Instance'"
            pInputText
            type="text"
            (input)="dt.filter($event.target.value, col, col.filterMatchMode)"
          />
        </th>
      </tr>
    </ng-template>
    <ng-template pTemplate="body" let-alert>
      <tr [pSelectableRow]="alert">
        <td>{{ alert.name }}</td>
        <td>{{ alert.instance }}</td>
        <td>{{ alert.severity }}</td>
        <td>{{ alert.summary }}</td>
        <td>{{ alert.state }}</td>
        <td>{{ alert.activeAt | date: "medium" }}</td>
      </tr>
    </ng-template>
  </p-table>
</div>

Мой component.model.ts:

export class AlertingDB {
  id: number;
  name: string;
  instance: string;
  severity: string;
  summary: string;
  state: string;
  activeAt: string;
}

А в моем component.service.ts:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Response } from "@angular/http";
import { environment } from "src/environments/environment";
import { Alerting } from "../models/alerting";
import { AlertingDB } from "../models/alerting-db";

@Injectable({
  providedIn: "root"
})
export class AlertingService {
  private AlertingUrl = environment.API_URL + "Alerting"; // URL to web api

  constructor(private http: HttpClient) {}

  getAllAlertsFromDB(): Observable<AlertingDB> {
    return this.http.get(this.AlertingUrl + "/getAll").pipe(
      map((response: AlertingDB) => {
        return <AlertingDB>response;
      })
    );
  }
  deleteAllAlertsFromDB(): Observable<AlertingDB> {
    return this.http.delete<AlertingDB>(this.AlertingUrl);
  }
}

Все функции работают очень хорошо, вы можете использовать мой код, если хотите, теперь проблема в том, что когда я использую фильтр, он ничего не фильтрует. Пример: здесь я получаю все экземпляры:

enter image description here

Но когда я пытаюсь отфильтровать, это дает мне 0 пункт:

enter image description here

В консоли нет ошибок, я хочу использовать этот фильтр. Любая помощь будет оценена, спасибо! :)

1 Ответ

0 голосов
/ 27 марта 2020

Вы пытаетесь отфильтровать свой столбец на основе col.filterMatchMode

В вашем компоненте cols - это массив строк, поэтому, когда мы доберемся до шаблона, col.filterMatchMode всегда будет undefined .

Вы можете либо явно указать режим фильтра в своем шаблоне:

<input
  *ngSwitchCase="'Instance'"
   pInputText
   type="text"
   (input)="dt.filter($event.target.value, col, 'in')"
 />

, либо изменить свой cols так, чтобы он содержал свойство filterMatchMode и name:

this.cols = [
  {name: "Name"},
  {name: "Instance", filterMatchMode: 'in'},
  {name: "Severity"},
  {name: "Summary"},
  {name: "State"},
  {name: "Active Date"}
];

и в вашем шаблоне:

<ng-template pTemplate="header" let-columns>
  <tr>
    <th *ngFor="let col of columns" [pSortableColumn]="col.name">
      {{ col.name }}
      <p-sortIcon
        [field]="col.name"
        ariaLabel="Activate to sort"
        ariaLabelDesc="Activate to sort in descending order"
        ariaLabelAsc="Activate to sort in ascending order"
      >
      </p-sortIcon>
    </th>
  </tr>
  <tr>
    <th *ngFor="let col of columns" [ngSwitch]="col.name">
      <input
        *ngSwitchCase="'Instance'"
        pInputText
        type="text"
        (input)="dt.filter($event.target.value, col.name, col.filterMatchMode)"
      />
    </th>
  </tr>
...