[英]Search in table without pipe Angular 6
我試圖在不使用任何管道的情況下在表內構建搜索。 這是我現在擁有的:
.ts
get filteredArray() {
if (this.searchValue.length === 0) {
return this.usersList
}
return this.usersList.filter((user) => {
return (this.searchValue.length > 0 ? this.searchValue.indexOf(user.name) !== -1 : true) ||
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.group) !== -1 : true) ||
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.age) !== -1 : true)
})
}
inputClick(searchText) {
if (searchText != "") {
this.searchValue.push(searchText)
} else {
this.searchValue.splice(0, 1)
}
}
.html
<input type="text" [(ngModel)]="searchText" (keyup.enter)="inputClick(searchText)">
<table>
<thead>
<tr>
<td><strong>Name</strong></td>
<td><strong>Group</strong></td>
<td><strong>Age</strong></td>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of filteredArray">
<td>{{ user.name }}</td>
<td>{{ user.group }}</td>
<td>{{ user.age }}</td>
</tr>
</tbody>
</table>
這可以正常工作(如果在input
鍵入內容並按ENTER,它將出現;如果刪除並按ENTER,它將恢復為初始數組)
如您所見,為此,我篩選了列表的每個字段:
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.name) !== -1 : true) ||
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.group) !== -1 : true) ||
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.age) !== -1 : true)
我的問題是:如何避免在return語句中使用所有字段? 因為在我的數據庫中,我有30多個字段,並且很難編寫30個不同的||
。
另外,如果我寫joh
而不是john
,如何修改代碼以仍然找到條目?
感謝您的時間! 在這里您可以看到我的項目的工作片段
您可以編寫一個函數遍歷所有字段並檢查所有字段。
containsValue(userObj, searchValue){
return Object.values(userObj).reduce((prev, cur) => {
cur = cur.toString();
return prev || cur.indexOf(searchValue) > -1;
}, false)
}
在您當前的功能中使用此方法
get filteredArray(){
...
return this.userList.filter((user) => this.containsValue(user, this.searchValue));
}
編輯:如果您不使用ES2017,則將Object.values()更改為Object.keys()並以userObj [cur]的形式獲取“ cur”值。 因此對於es2017之前的版本:
containsValue(userObj, searchValue){
return Object.keys(userObj).reduce((prev, cur) => {
let temp = userObj[cur].toString();
return prev || temp.indexOf(searchValue) > -1;
}, false);
}
我本來可以使用反應式的FormControl,但這不是您要的。
我修改了解決方案以獲取用戶屬性,然后檢查一下searchText是否與您的用戶屬性之一中的值匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.