角度:TypeScript表中的搜索栏

时间:2019-03-08 09:46:34

标签: javascript html angular typescript angular-ngmodelchange

我已经完成了一个简单的CRUD应用程序,现在我必须添加一个搜索栏来过滤我的表格,并向我显示与我输入的字母相同的行。

我不知道该在组件中做什么,我用管道和过滤器看到了不同的东西,但是我无法使其适应我的项目。

我想知道是否有一种方法可以在我的component.ts中实现,而无需创建新方法。

COMPONENT.HTML

<div class="container">
  <ul class="table-wrapper">
    <div class="table-title">
      <div class="row">
        <div class="col-sm-4">
          <button *ngIf="metadata && metadata.addMD" (click)="addFunc(metadata)">{{metadata.addMD.label}}</button>
          <div class="show-entries">
            <span>Show</span>
            <label>
              <select [(ngModel)]="pageSize">
                <option *ngFor="let maxPerPage of rowsOnPageSet"
                        (click)="maxElements(maxPerPage)">{{maxPerPage}}</option>
              </select>
            </label>
            <span>users</span>
          </div>
        </div>

        <div class="col-sm-4">
          <h2 class="text-center">Users <b>Details</b></h2>
        </div>

        <div class="col-sm-4">
          <div class="search-box">
            <div class="input-group">
              <span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span>
--> //HERE I HAVE TO ADD THE FUNCTION OR SOMETHING ELSE
             <input type="text" class="form-control" [(ngModel)]="searchVal"
                 (ngModelChange)='checkSearchVal()'  placeholder="Search&hellip;">
            </div>
          </div>
        </div>
      </div>
    </div>

    <table class="table table-bordered">
      <thead>
      <tr>
        <th *ngFor="let col of columns" (click)="sortTable(col)">{{col}}
          <i *ngIf="col === columnSorted && !direction" class="material-icons">keyboard_arrow_up</i>
          <i *ngIf="col === columnSorted && direction" class="material-icons">keyboard_arrow_down</i>
        </th>
        <th>Actions</th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let user of users | paginate: {itemsPerPage: pageSize,
                                               currentPage: page,
                                               totalItems: users.length}">
        <td *ngFor="let col of columns">{{user[col]}}</td>
        <td>
          <button [ngClass]="getClassCondition(act.actionType)" *ngFor="let act of actions"
                  (click)="actionFunc(act, user)">{{act.label}}</button>

        </td>

      </tr>
      </tbody>
    </table>

    <div align="center">
      <!--<div class="hint-text">Showing <b>{{totUsersPerPage}}</b> out of <b>{{users.length}}</b> entries</div>-->
      <ul align="center">
        <pagination-controls (pageChange)="pageChanged($event)"></pagination-controls>
      </ul>
    </div>

  </ul>
</div>

COMPONENT.TS,在这里,我必须创建适用于我的应用的正确方法。

    export class DynamicTableComponent implements OnInit {

  constructor(private userService: UserService,
              private resourcesService: ResourcesService,
              private router: Router) {
  }

  @Input()
  users = [];
  @Input()
  columns: string[];
  @Input()
  actions = [];
  @Input()
  metadata: any;
  @Input()
  class;

  direction = false;
  columnSorted = '';
  public rowsOnPageSet = ['5', '10', '15', '20', '25'];
  page = 1;
  private pageSize = 5;
  searchVal = '';

  /*totalPages = Math.trunc(this.users.length / this.pageSize);
  totUsersPerPage = this.pageSize;*/

  ngOnInit() {
  }

  actionFunc(action, element: any) {
    if (action.actionType === 'DELETE') {
        /*...*/
      }
    }
    if (action.actionType === 'GO_TO') {
        /*...*/
    }
  }

  addFunc(metadata) {
    if (metadata.addMD.actionType === 'ADD_TO') {
       /*...*/
    }
  }

  maxElements(maxPerPage) {
    this.rowsOnPageSet = maxPerPage;
  }

  sortTable(param) {
    /*...*/
  }

  getClassCondition(act) {
    return act === 'DELETE' ? this.class = 'btn btn-danger' : 'btn btn-primary';
  }

  pageChanged($event: number) {
     /*...*/
  }

checkSearchVal() {
    this.users.slice();
    const filteredUsers: User[] = [];
    if (this.searchVal && this.searchVal !== '') {
      for (const selectedUser of this.users) {
        if (selectedUser.firstName.toLowerCase().search(this.searchVal.toLowerCase()) !== -1 ||
          selectedUser.lastName.toLowerCase().search(this.searchVal.toLowerCase()) !== -1) {
          filteredUsers.push(selectedUser);
        }
      }
      this.users = filteredUsers.slice();
    }
  }

}

数据结构: in.memory-data.service.ts

import { InMemoryDbService } from 'angular-in-memory-web-api';
import { User } from './user';
import { Injectable } from '@angular/core';

export const COLUMNS = ['id', 'firstName', 'lastName', 'age'];

@Injectable({
  providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const USERS = [
      {id: 1, firstName: 'Sergio', lastName: 'Rios', age: 23},
      {id: 2, firstName: 'Alessandro', lastName: 'Amodeo', age: 23},
      {id: 3, firstName: 'Antonio', lastName: 'Vitolo', age: 23},
      {id: 4, firstName: 'Andrea', lastName: 'Bellati', age: 24},
      {id: 5, firstName: 'Yvette', lastName: 'Arevalo Godier', age: 42},
      {id: 6, firstName: 'Federico', lastName: 'Belloni', age: 41},
      {id: 7, firstName: 'Claudio', lastName: 'Tornese', age: 24},
      {id: 8, firstName: 'Diana', lastName: 'Budascu', age: 25},
      {id: 9, firstName: 'Veronica', lastName: 'Moreira', age: 25},
      {id: 10, firstName: 'Sirak', lastName: 'Guida', age: 25},
      {id: 11, firstName: 'Marina', lastName: 'Righetti', age: 22},
      {id: 12, firstName: 'Giorgia', lastName: 'Secchi', age: 22},
      {id: 13, firstName: 'Simone', lastName: 'Bocallari', age: 24},
    ];
    return {USERS};
  }
}

user.ts

export class User {
  id: number;
  firstName: string;
  lastName: string;
  age: number;
}

2 个答案:

答案 0 :(得分:3)

只需创建一个PIPE.ts文件来过滤表:

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

@Pipe({ 
    name: 'filterAll'
})
export class FilterPipe implements PipeTransform {
  transform(value: any, searchText: any): any {
    if(!searchText) {
      return value;
    }
    return value.filter((data) => this.matchValue(data,searchText)); 
  }

  matchValue(data, value) {
    return Object.keys(data).map((key) => {
       return new RegExp(value, 'gi').test(data[key]);
    }).some(result => result);
  }
 }

声明中将FilterPipe添加到 app.module.ts  并将其添加到您的 component.html

  <form id="searchForm">
    <div class="form-group">
        <div class="input-group" id="filterAll">
          <div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
          <input type="text" class="form-control" name="searchString" placeholder="Search..." [(ngModel)]="searchString">
        </div>
    </div>
</form>

然后将管道添加到表的TR中,如下所示:

 <tr *ngFor="let user of users | paginate: {itemsPerPage: pageSize,
                                           currentPage: page,
                                           totalItems: users.length} | filterAll: searchString">

抱歉,我忘记了component.ts文件: 您需要将searchString变量设置为:

public searchString: string;

答案 1 :(得分:1)

我看到您得到了答案... here是另一种解决问题的方法,如评论中所述...

summary_writer = tf.summary.FileWriter("someName")

for event in tf.train.summary_iterator("somePath"):
    if (event.step > 1000000):
        summary = tf.Summary()
        shifted_step = event.step - 1000000
        for value in event.summary.value:
            print(value.tag)
            if (value.HasField('simple_value')):
                print(value.simple_value)
                summary.value.add(tag='{}'.format(value.tag),simple_value=value.simple_value)

        summary_writer.add_summary(summary, shifted_step)
        summary_writer.flush()

更新:移动了此。USERS= FilteredUsers.slice();在IF内

更新:2 :与forEach和For-Of相同的代码(以消除TSLint错误)