【问题标题】:Angular - filtering a table using pipeAngular - 使用管道过滤表
【发布时间】:2020-04-15 21:02:23
【问题描述】:

我是 Angular 新手,正在尝试制作我的第一个全栈程序,我正在使用 Angular 和 Spring Boot。 我正在尝试从我的服务器获取文件并使用角度将它们显示在表格中。 我设法做到了,但现在我想在桌子上添加一个过滤选项,我正在使用管道来这样做,但它似乎不起作用,我遇到的问题是在我的

*ngFor="let file of files | async ; let i = index ">

找不到写出所有条件而不报错的方法

这是我的客户端代码: html部分:

<div class="panel panel-default">
<div class="panel-heading">
    <h1>Files</h1>
</div>
<div class="panel-body">

    <form>
        <div class="form-group">
          <div class="input-group">
            <div class="input-group-addon">
              <i class="glyphicon glyphicon-search"></i>
            </div>
            <input
              type="text"
              class="form-control"
              name="searchString"
              placeholder="Type to search..."
              [(ngModel)]="searchString"
            />
          </div>
        </div>
      </form>
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th>Location</th>
                <th>Timestamp</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let file of files | async ; let i = index ">
                <th scope="row">{{ i + 1 }}</th>
                <td>{{file.location}}</td>
                <td>{{file.timestamp}}</td>
                <td>{{file.name}}</td>
            </tr>
        </tbody>
    </table>
</div>

和管道:

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({
 name: 'filter'
 })
 @Injectable()
 export class SearchPipe implements PipeTransform {
 transform(items: any[], field: string, value: string): any[] {
  if (!items) {
  return [];
    }
   if (!field || !value) {
    return items;
  }

return items.filter(singleItem =>
  singleItem[field].toLowerCase().includes(value.toLowerCase())
);

} }

以及列出 ts 的文件:

export class FileListComponent implements OnInit {

files: Observable<File[]>;
searchString: string;
constructor(private fileService: FileService) {}

ngOnInit() {
  this.reloadData();
 }

reloadData() {
  this.files = this.fileService.getFileList();
 }

}

我从本教程中获得了有关管道部分的帮助: https://offering.solutions/blog/articles/2016/11/21/how-to-implement-a-table-filter-in-angular/

它说 ngFor 应该是这样的:

<tr
*ngFor="let food of foods | filter : 'name' : searchString; let i = index"

>

但由于我也有| async,所以我无法满足所有条件.. 我猜这就是问题所在..

我怎样才能写出类似&lt;tr *ngFor="let file of files | async ; filter : 'name' : searchString; let i = index "&gt; 的东西?

任何帮助将不胜感激

【问题讨论】:

    标签: angular pipe


    【解决方案1】:

    像这样使用括号:

    *ngFor="let food of (foods | async) | filter : 'name' : searchString; let i = index"
    

    看看StackBlitz demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-29
      • 2018-06-16
      • 2018-02-02
      • 1970-01-01
      • 2017-06-09
      • 2016-01-12
      • 1970-01-01
      相关资源
      最近更新 更多