角度-使用管道过滤表格

时间:2020-04-15 21:02:23

标签: angular pipe

我对angular并不陌生,并且尝试制作我的第一个全栈程序,我使用了angular和spring boot。 我正在尝试从服务器获取文件并使用angular在表中显示它们。 我设法做到了,但是现在我想在表上添加一个填充选项,并且我正在使用管道来执行此操作,但它似乎无法正常工作,我遇到的麻烦在于< / p>

*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,所以我无法满足所有条件。 我猜是问题所在。

我怎么写类似<tr *ngFor="let file of files | async ; filter : 'name' : searchString; let i = index ">的东西?

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

像这样使用括号:

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

看看StackBlitz demo

相关问题