使用* ngFor遍历数组,同时还过滤特定属性

Mui*_*rik 1 javascript arrays typescript angular-ng-if angular

在我的Angular 2应用程序中,我想知道是否有一种方法可以遍历数组,同时还可以过滤*ngFor块中的某个属性。所以语法看起来像这样:

<ng-template *ngFor="let flag['completed === false'] of service.flags">
    <span class="standard-flag" 
        [class.hold-flag]="flag?.flagType === 'hold'">Flag
    </span>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

因此,基本的逻辑是,对于数组中存在的每个对象(“ flag”是一个对象),将“ completed”属性设置为“ false”,则返回该值。而不是首先遍历数组,然后使用* ngIf进行进一步过滤,如果可以同时在* ngFor块中做这件事会很好(在我的特定情况下非常有用)。可能?

我之所以对这种构造特别感兴趣,是因为我只想返回“ completed”为“ false”的第一个值,并且可以使用* ngFor中的“ let i = index”来处理它。在这种情况下阻止。但是我不想返回所有标志对象中的第一个,只是返回“ completed”属性设置为“ false”的标志对象。

Deb*_*ahK 5

使用管道进行过滤不是一个好主意。请参阅此处的链接:https : //angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

而是在组件中添加代码以执行过滤。然后对过滤的数据使用ngFor。

下面是一个例子。然后,您将在此示例中仅对filteredProducts使用ngFor。

import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}
Run Code Online (Sandbox Code Playgroud)