我知道这是个问题但我忘了这个语法是怎么工作的..。我尝试过很少的东西,但它没有真正起作用.有人能帮我吗?
我有一个数组:
products = [
{name: banana},
{name: apple},
{name: orange}
]我有这个搜索输入
<input (keydown)="filterProducts($event)" placeholder="Ex. Banana">这是我的职责
filterProducts({target: {value}}) {
this.products.filter(filtered => {
const filter = filtered.name.includes(value)
console.log(filter)
})
}我在控制台日志中得到的只是真或假,但我希望得到一个新数组,其中只包含以搜索输入的字母开头的项.谢谢!
注:禁止使用管道
发布于 2020-12-23 11:01:17
filtered.name.includes(value)是一个布尔函数,所以它在console.log中显示bool。
如果你这样做了
filterProducts({target: {value}}) {
const filteredProducts = this.products.filter(filtered=>filtered.name.includes(value))
console.log(filteredProducts) // this prints the array of filtered
}您将看到该数组被过滤。
发布于 2020-12-23 11:23:19
只是分享我的实现使用debounce指令。也许能帮上忙。
import { Component, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
search: any;
products = [{ name: "banana" }, { name: "apple" }, { name: "orange" }];
searchResult: any;
onSearch(event: any) {
const value = event.target.value;
if (value.length >= 3) {
this.searchResult = this.products.filter(filtered =>
filtered.name.includes(value)
);
}
console.log(this.searchResult);
}
}<input id="search" type="text" [(ngModel)]="search" appDebounce (debounce)="onSearch($event)" [delay]="300" />
Stackblitz:https://stackblitz.com/edit/angular-ivy-pqbttb?file=src%2Fapp%2Fapp.component.ts
https://stackoverflow.com/questions/65422601
复制相似问题