2017-02-20 122 views
0

我想爲帶有搜索框的表格創建一個簡單的包裝(並在未來進行排序)。所以,用戶不必創建管道等,只需使用* ngFor。我想知道如何去做,因爲下面的例子不會更新視圖。在Angular 2中沒有管道過濾

HTML

<my-table [data]="statuses"> 
    <thead> 
     <th>header 1</th> 
    </thead> 
    <tbody> 
     <tr *ngFor="let status of statuses"> 
      <td>{{status.username}}</td> 
      <td>{{status.username}}</td> 
     </tr> 
    </tbody> 
</my-table> 

組件:

import { Component, Input, OnInit, AfterViewInit, ContentChild } from '@angular/core'; 
import { MyTableService } from '../services/my-table.service' 

@Component({ 
    selector: 'my-table', 
    //styleUrls: [ '../styles/my-table.css' ],  
    templateUrl: '../templates/my-table.template.html', 
    providers: [MyTableService] 
}) 
export class MyTableComponent implements OnInit { 
    @Input() data: any; 

    constructor(
     private myTableService: MyTableService 
     ) {  
    } 

    public filter(event) { 
     this.data = this.myTableService.filter(this.data, event.target.value) 
    } 

    public ngOnInit() {  

    } 

} 

HTML組件

<div style="width: 100%; float: left"> 
    <input type="text" (keyup)="filter($event)"/> 
</div> 
<div style="width: 100%; float: left"> 
    <table> 
     <ng-content> 
     </ng-content> 
    </table> 
</div> 
+0

下面的例子? :) – mxii

+0

嗯,堆棧提交表格時,我按下輸入:/我編輯了我的帖子:) –

+0

你必須實現一個管道過濾你的表。爲什麼你不想使用管道?如果你想過濾表格,我可以給你一個例子。也只是添加一些代碼,以顯示您迄今爲止所做的。 – gon250

回答

0

嘗試這樣的:

export class MyTableComponent implements OnInit { 

    @Input() data: any; 
    private _filteredData: any; 

    constructor(private myTableService: MyTableService) {  
    } 

    public filter(event) { 
     this._filteredData = this.myTableService.filter(this.data, event.target.value) 
    } 

    public ngOnInit() {  

    } 
} 
<tr *ngFor="let status of _filteredData"> 

保持您的原始數據原樣,並使用其他屬性過濾數據。

+0

它不起作用 –

+0

爲什麼?錯誤?有什麼問題? :) – mxii

+0

將提供plunker .. – mxii