计算表/ * ngFor中的行数(总计/根据值)

时间:2018-04-26 03:20:28

标签: angular typescript

任何人都可以告诉我如何获取此表中行的总值,另外我想要符合列属性的真实或错误条件的行的值。

https://stackblitz.com/edit/angular-g9twrl?embed=1&file=app/app.component.html

enter image description here

3 个答案:

答案 0 :(得分:4)

您也可以使用此

  

HTML

<div class="container mt-4">

         <p>
          Total rows: {{ getRowsValue(null) }} <br>
          State Active (true): {{ getRowsValue(true) }} <br>
          State Inactive (false): {{ getRowsValue(false) }}
          </p>

          <table class="table">
            <thead>
              <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Description</th>
            <th scope="col">State</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let item of myItems; let i = index">
            <th>{{ i + 1 }}</th>
            <td>{{ item.name }}</td>
            <td>{{ item.description }}</td>
            <td>
              <mat-slide-toggle [checked]="item.state" (change)="item.state = !item.state"></mat-slide-toggle>
            </td>
              </tr>
            </tbody>
          </table>
        </div>
  

组件

import { Component } from '@angular/core';

        @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
          name = 'Angular 5';

          myItems: any[];

          constructor() {
            this.myItems = [
              { name: 'item 1', description: 'description 1', state: false },
              { name: 'item 2', description: 'description 2', state: true },
              { name: 'item 3', description: 'description 3', state: false },
              { name: 'item 4', description: 'description 4', state: true },
              { name: 'item 5', description: 'description 5', state: true },
            ]
          }

          public getRowsValue(flag) {
            if (flag === null) {
              return this.myItems.length;
            } else {
              return this.myItems.filter(i => (i.state == flag)).length;
            }
          }

        }

答案 1 :(得分:1)

将这些getter添加到您的组件中:

get totalRows(): number {
  return this.myItems.length;
}

get activeRows(): number {
  return this.myItems.filter(i => i.state).length;
}

get inactiveRows(): number {
  return this.myItems.filter(i => !i.state).length;
}

在你的模板中:

<p>
  Total rows: {{ totalRows }} <br>
  State Active (true): {{ activeRows }} <br>
  State Inactive (false): {{ inactiveRows }}
</p>

如果您希望滑块更新活动/非活动计数,则需要在切换滑块时更新基础状态:

<mat-slide-toggle [checked]="item.state" (change)="item.state = !item.state">
</mat-slide-toggle>

答案 2 :(得分:0)

使用ProjektNummmer = 17016还将显示过滤长度。