我想为带有搜索框的表创建一个简单的包装器(并在将来进行排序)。因此,用户不必创建管道等,只需使用* ngFor。我想知道如何做到这一点,因为下面的示例不会更新视图。
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 :(得分: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">
保持原始数据不变,并使用其他属性过滤数据。