如何使用Angular过滤表中的行?

时间:2018-08-05 18:36:49

标签: angular

因此,我正在使用angular来显示数据库中的一些存储信息。 我想在表中仅显示具有特定信息的行。例如,仅显示状态为“已接受”的行。

       <div class="container" >
         <div class="row">

           <table class="table table-dark">
                <thead>
          <tr>
              <th>Boat type</th>
              <th>Service</th>
              <th>Boat Location</th>
              <th>Job type</th>
              <th>Status</th>
        </tr>
          </thead>   
          <tbody>
           <tr *ngFor="let boat of boats" >
           <td>{{ boat.boatType }}</td>
           <td>{{ boat.service }}</td>
           <td>{{ boat.location }}</td>
           <td>{{ boat.jobType }}</td>
           <td>{{ boat.status }}</td>


         </tr>


        </tbody>
      </table>
  </div>
</div>

4 个答案:

答案 0 :(得分:5)

.ts文件中,您可以执行以下操作:

this.boats = this.boats.filter((boat) => boat.status === 'Accepted')

这将删除所有没有该状态的项目

答案 1 :(得分:3)

根据您的情况,可以使用 angular pipe

例如,您要在ngfor内过滤数组

首先,您要像这样定义管道

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

@Pipe({name: 'exampleFilter'})

export class ExamplePipe implements PipeTransform {
  transform(arr) {
    return arr.filter((boat) => boat.status === 'Accepted');
  }
}

然后像这样将其导入到您的模块[示例:AppModule.ts]

import { ExamplePipe } from './examplePipe.pipe'; // import our pipe here

@NgModule({
  ...
  declarations: [ ... , ExamplePipe ], // include example pipe here
  ...
})

export class AppModule { }

然后您可以像这样使用它

<tr *ngFor="let boat of boats | exampleFilter" >
  <td>{{ boat.boatType }}</td>
  <td>{{ boat.service }}</td>
  <td>{{ boat.location }}</td>
  <td>{{ boat.jobType }}</td>
  <td>{{ boat.status }}</td>
</tr>

答案 2 :(得分:2)

您可以通过对ng-container循环使用ngFor并在ngIf元素上应用tr条件来过滤模板中的行。请注意,ng-container本身未在HTML输出中呈现。

<tbody>
  <ng-container *ngFor="let boat of boats" >
    <tr *ngIf="boat.status === 'Accepted'">
      <td>{{ boat.boatType }}</td>
      <td>{{ boat.service }}</td>
      <td>{{ boat.location }}</td>
      <td>{{ boat.jobType }}</td>
      <td>{{ boat.status }}</td>
    </tr>
  </ng-container>
</tbody>

有关演示,请参见this stackblitz

答案 3 :(得分:1)

如果您不想更改this.boats数组而只在视图中不显示某些行:

       <div class="container" >
         <div class="row">

           <table class="table table-dark">
                <thead>
          <tr>
              <th>Boat type</th>
              <th>Service</th>
              <th>Boat Location</th>
              <th>Job type</th>
              <th>Status</th>
        </tr>
          </thead>   
          <tbody>
           <tr *ngFor="let boat of boats" >
           <td *ngIf="boat.status === 'Accepted'">{{ boat.boatType }}</td>
           <td *ngIf="boat.status === 'Accepted'">{{ boat.service }}</td>
           <td *ngIf="boat.status === 'Accepted'">{{ boat.location }}</td>
           <td *ngIf="boat.status === 'Accepted'">{{ boat.jobType }}</td>
           <td *ngIf="boat.status === 'Accepted'">{{ boat.status }}</td>

         </tr>


        </tbody>
      </table>
  </div>
</div>