我使用forEach简化了逻辑,并检查我从输入中接收的值是否包含我要应用的任何搜索条件。我希望这将有助于您解释是否遇到类似情况。
我在角度应用程序中有一个搜索输入,应该将输入数据与不同的对象属性进行比较
<div class="forms">
<div class="search-wrapper">
<input
class="search"
[ngClass]="{'searching': searching}"
type="text"
(input)="changeSearch($event.target.value)"
/>
<label class="">
<span>Rechercher</span>
</label>
</div>
</div>
我使用的逻辑如下
public changeSearch(searchTerm: string) {
this.searching = !!searchTerm;
if (!this.searching) {
this.orders.forEach(order => {
order.show = true;
});
return;
}
const extendSearchIn = ['order_number', 'transaction.item.product.name'];
this.orders.forEach(order => {
order.show = true;
extendSearchIn.forEach(property => {
this.searchByProperty(order, property, searchTerm);
});
});
}
public searchByProperty(order, property, searchTerm) {
const prop = this.getSearchProperty(order, property);
if (prop === undefined) { return false; }
return (<String>prop.toLowerCase()).startsWith(searchTerm.toLowerCase());
}
public getSearchProperty(item: object, property: string) {
let itemCopy = Object.assign({}, item);
let result: any;
const props = property.split('.');
props.forEach(prop => {
if (itemCopy !== undefined) {
itemCopy = itemCopy[prop];
}
});
result = itemCopy !== undefined ? itemCopy : result;
return result;
}
并且每个对象'order'的结构如下所示>>
{ "functional_id": "202006101058160012400000SD4AYAA1", "transactions": [ { "quantity": 2, "price": 140, "item": { "name": "Carton", "description": "+ 2 recharges", "product": { "name": "Coffret rouge" } }, "amount": 280 }, { "quantity": 2, "price": 140, "item": { "name": "10 coffrets", "description": "+ 2 recharges", "product": { "name": "Coffret gris" } }, "amount": 280 }, { "quantity": 2, "price": 60, "item": { "name": "PACK N°1 comprenant :", "description": "6 modèles", "product": { "name": "AfuBOX", "description": "60,8 x 39,5 x 16,5 cm" } }, "amount": 120 } ], "show": true, "date": "10/06/2020", "order_number": "105816", "overallAmount": 680 }
您需要将'show'属性设置为false,以便隐藏不符合在搜索字段中输入的内容的内容有人让我知道我的错误在哪里。预先谢谢你
我在角度应用程序中有一个搜索输入,应该将输入数据与不同的对象属性进行比较
我使用forEach简化了逻辑,并检查我从输入中接收的值是否包含我要应用的任何搜索条件。我希望这将有助于您解释是否遇到类似情况。
public changeSearch(searchTerm: string) {
this.searching = !!searchTerm;
if (!this.searching) {
this.orders.forEach(order => {
order.show = true;
});
return;
}
this.orders.forEach(order => {
order.show = true;
this.searchByProperty(order, searchTerm);
});
}
public searchByProperty(order, searchTerm) {
const id = (order.order_number + '');
const amount = (order.overallAmount + '');
order.transactions.forEach(items => {
const title = items.item.product.name.toLowerCase();
if (title.includes(searchTerm) || id.includes(searchTerm) || amount.includes(searchTerm)) {
order.show = true;
} else {
order.show = false;
}
});
}
我使用forEach简化了逻辑,并检查我从输入中接收的值是否包含我要应用的任何搜索条件。我希望这将有助于您解释是否遇到类似情况。