我有一个表,该表的数据来自循环,我还需要向其中添加搜索功能,我试图创建自定义管道,但是它不起作用,有人可以帮我吗,这是下面的代码< / p>
<input type="text" placeholder="search..">
<table class="table border">
<thead>
<tr>
<ng-container *ngFor="let column of columns; let i = index">
<th>{{ column }}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of groups;let i = index" >
<td>{{row.name}}</td>
<td>{{row.items}}</td>
</tr>
</tbody>
</table>
import { Component,ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
columns = ["name", "Items"];
groups=[
{
"id": 1,
"name": "pencils",
"items": "red pencil"
},
{
"id": 2,
"name": "rubbers",
"items": "big rubber"
},
{
"id": 3,
"name": "rubbers1",
"items": "big rubber1"
},
];
}
答案 0 :(得分:1)
首先,像这样更新您的html输入和表数组
<input type="text" placeholder="search.." (input)="onChange($event.target.value)" >
<table class="table border">
<thead>
<tr>
<ng-container *ngFor="let column of columns; let i = index">
<th>{{ column }}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of viewedGroups;let i = index" >
<td>{{row.name}}</td>
<td>{{row.items}}</td>
</tr>
</tbody>
</table>
之后在您的ts
viewedGroups = [];
...
ngOnInit(){
this.viewedGroups = this.groups;
}
onChange(value){
this.viewedGroups = this.groups.filter(a=>a.name.toLowerCase().search(value.toLowerCase())>-1 || a.items.toLowerCase().search(value.toLowerCase())>-1)
}
请检查example