2017-01-07 30 views
0

我有一個表,它在ngOnInit()方法中初始化獲取API數據。Angular 2 - 如何使用搜索框更新組件中的表格?

此表格附帶一個過濾器(輸入文本),其中與一個函數相關聯,該函數調用一個生成過濾器的API方法。

這是我的組件:

[..] 
@Component({ ... }) 
export class DataComponent implements OnInit { 
    datas:  Courier[] = []; 

    constructor(private _dataService: DataService){} 

    ngOnInit() { 
    this.loadData(); 
    } 

    loadData() { 
    this.isLoading = true; 
    this._dataService.getData() 
     .then(data => { 
     this.couriers = this.datas.concat(data); 
     this.isLoading = false; 
     this.error = false; 
     }) 
     .catch(() => { 
     this.error = true; 
     this.isLoading = false; 
     }) 
    } 

    searchData(searchKey: string){ 
    this._dataService.getData(searchKey) 
     .then(data => { 
     this.couriers = this.datas.concat(data); 
     this.isLoading = false; 
     this.error = false; 
     }) 
     .catch(() => { 
     this.error = true; 
     this.isLoading = false; 
     }); 
    } 

的搜索方法有效,因爲它讓我看到相應的數據,並將其顯示在表格中。 問題是它不會用初始數據來冷卻整個表格;將過濾的結果添加到表格中。

這是我的html:

<table #datatable id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> 
    <thead> 
    <tr> 
     <th>#</th> 
     <th>Name</th> 
     <th>Last Name</th> 
     <th>Email</th> 
     <th></th> 
    </tr> 
    </thead> 
    <tbody *ngFor="let data of datas"> 
     <tr> 
     <td class="courier_id">{{ data.id }}</td> 
     <td class="courier_name">{{ data.name }}</td> 
     <td class="courier_last_name">{{ data.last_name }}</td> 
     </tr> 
    </tbody> 
</table> 

的搜索方法,在我的附加組件,而不是刷新<tbody><tr>。我究竟做錯了什麼?

+1

您正在使用'this.datas.concat(data);'它將連接兩個數組,而不是將原來的 – Chandermani

回答

0

首先,tbody不應該重複,你可以把* ngFor放在tr上。

其次,contat連接兩個數組例如:

arr1 = [1,2,3] 
arr2 = [4,5,6] 
arr3 = arr1.concat(arr2) // [1,2,3,4,5,6] 

你應該例如使用推來代替:

datas = [] 
data = [1,2,3] 
data2 = [4,5,6] 
datas.push(data); 
datas.push(data2);// [[1,2,3],[4,5,6]] 

祝您好運!

相關問題