Фильтр не возвращает результаты в Angular Материал - PullRequest
0 голосов
/ 19 февраля 2020

Я пытаюсь отфильтровать результаты из таблицы, используя Material NG, но не получаю никаких результатов и ошибок.

Вот мой код

  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = {};

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: ItemsInterface) => {
      this.dataSource = res;
      this.dataSource = new Array(res);
      console.log(this.dataSource[0]);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }


  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource[0].filter = filterValue.trim().toLowerCase();
  }

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (keyup)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>
  <table mat-table [dataSource]="dataSource[0]" class="mat-elevation-z8">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let element"> <a mat-raised-button href="{{element.url}}" color="primary">Go to site</a></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

Мне интересно, это формат источника данных, который у меня есть. Это выглядит так.

[
  {
    "name": "Ajax",
    "description": "a technology for asynchronous HTTP requests",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AJAX.md"
  },
  {
    "name": "AMD",
    "description": "a standard defining how to load JavaScript libraries or modules asynchronously",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AMD.md"
  },
  {
    "name": "AngularJS",
    "description": "a structural framework for dynamic web apps",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/ANGULARJS.md"
  }
]

Я сделал репо здесь, чтобы воспроизвести проблему. https://github.com/dhameergovind/NG-Starter.git

1 Ответ

1 голос
/ 19 февраля 2020

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Constants } from '../constants/constants';
import { ItemsInterface } from '../models/data';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

 constructor(private httpClient: HttpClient) {
 }

  getData(): Observable<ItemsInterface[]> {
    return this.httpClient.get<ItemsInterface[]>(Constants.API_ENDPOINT + 'data.json');
  }

}

app.component.ts

import { Component, OnInit, ViewChild , AfterViewInit} from '@angular/core';
import { ApiService } from './services/api.service';
import { ItemsInterface } from './models/data';
import { MatPaginator, MatTableDataSource } from '@angular/material';
export interface SourceDataType {
  name: string;
  description: string;
  markdown: string;
  html: string;
  url: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit , AfterViewInit{
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  ELEMENT_DATA: SourceDataType[];
  title = 'NG PWA';
  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = new MatTableDataSource<SourceDataType>(this.ELEMENT_DATA);
  public loading = false;
  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: SourceDataType[]) => {
      this.dataSource = new MatTableDataSource<SourceDataType>(res);
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }
  ngAfterViewInit() {
    setTimeout(() => this.dataSource.paginator = this.paginator);
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

app.component. html

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <span>Data</span>
  </mat-toolbar-row>
</mat-toolbar>
<main>

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (input)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="url">
      <th mat-header-cell *matHeaderCellDef> URL </th>
      <td mat-cell *matCellDef="let element"> <a mat-raised-button href="{{element.url}}" color="primary">Go to site</a></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

</main>

<router-outlet></router-outlet>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '3px' }"></ngx-loading>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...