您好,我是Angular的新手,目前正在研究一种对使用* ngFor创建的数组进行排序的方法。
我希望能够使用input
复选框进行过滤。我已经在对象上设置了属性……
PersonalInvestment: boolean;
这是为了定义类型,但是基于这个布尔值是什么,我要么想显示对象,要么要从数组中隐藏对象。我一直在学习Deborah Kurata的Pluralsight课程,在她的教程中,她根据输入到输入栏中的字符串值过滤数组。
这是她使用的获取和设置代码以及用于过滤的函数:
get listFilter(): string {
return this._listFilter;
}
set listFilter(value: string) {
this._listFilter = value;
this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
}
和功能performFilter
在组件的更下方:
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
因此,由于我的知识有限,我尝试使用类似的方法:
_personalFilter: boolean;
get personalFilter(): boolean {
return this._personalFilter;
}
set personalFilter(value: boolean){
this._personalFilter = value;
this.filteredBrands = this.personalFilter ? this.performFilter(this.personalFilter) : this.brands;
}
和我的功能:
performFilter(filterBy: boolean): Brands[] {
return this.brands.filter((brand: Brands) =>
brand.PersonalInvestment.valueOf = function () {
return this.filterBy;
});
}
我当前收到此错误:
我显然知道我的代码根本上是错误的,但这对我来说是一个全新的概念,到目前为止,StackOverflow上没有任何帮助。提前非常感谢您。
编辑:
这是我的输入框:
<input type="checkbox" name="Personal" value="Personal" [(ngModel)]="personalFilter"/> Personal<br />
这是* ngFor的div的开始:
<div *ngFor="let brand of filteredBrands">
答案 0 :(得分:0)
更改为此:
function performFilter(filterBy: boolean): any[] {
return this.brands.filter((brand: any) =>
brand.PersonalInvestment = filterBy);
}
答案 1 :(得分:0)
我设法找到一种通过输入框过滤列表的方法:
这是HTML中输入框之一的示例:
{
"Id": 5,
"Title": "5th Brand Test With Advanced Property",
"Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sollicitudin ornare lectus, quis gravida tortor venenatis nec. ",
"Properties": ["personal", "listedItems"],
},
然后在我的JSON中,我有一张要附加到我要过滤的卡片上的属性列表,如下所示:
brands: ExploreCards.IBrand[];
visibleBrands: ExploreCards.IBrand[] = [];
filteredProperties = [];
checkValue(event: any, property: string) {
if (event == true) {
this.filteredProperties.push(property);
for (var i = this.filteredProperties.length - 1; i >= 0; i--) {
if (this.filteredProperties[i] == property) {
this.visibleBrands = this.brands.filter(item => item.Properties.some(property => this.filteredProperties.indexOf(property) > -1));
}
}
} else {
for (var i = this.filteredProperties.length - 1; i >= 0; i--) {
if (this.filteredProperties[i] == property) {
this.filteredProperties.splice(i, 1);
}
}
this.visibleBrands = this.brands.filter(item => item.Properties.some(property => this.filteredProperties.indexOf(property) > -1));
}
if (this.filteredProperties.length === 0) {
this.visibleBrands = this.brands;
}
}
ngOnChanges() {
this.visibleBrands = this.brands.slice(0);
}
ngOnInit(): void {
this.brands = this.brandService.getBrands();
this.visibleBrands = this.brands;
}
然后我以以下方式在我的组件中对其进行过滤:
{{1}}
希望这对以后的人有所帮助! :)