2017-08-01 23 views
1

過濾在我的角2的應用程序,我想知道如果有一種方法,我可以遍歷數組,同時在*ngFor塊上的某些屬性過濾。因此,語法將是這個樣子:使用* 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> 

所以基本上的邏輯是,爲每個對象(「標誌」是一個對象)存在的數組,其中「已完成」屬性設置爲「假「,返回該值。如果我可以在* ngFor塊中執行這兩個操作,那麼不要先對數組進行迭代,然後使用* ngIf進一步進行過濾,否則它會很好(對我的特殊情況非常有用)。可能?

我之所以對這種結構感興趣,是因爲我想只返回「完成」爲「假」的第一個值,我可以用「let i = index」在這種情況下,在* ngFor塊中。但我不想返回所有標誌對象的第一個,只是將「完成」屬性設置爲「false」的標誌對象。

+2

您可以實現PipeTransform,並在使用它NG-如果作爲過濾 https://angular.io/guide/pipes – Jocket

+1

請使用管道這裏所指出的@Jocket看看這個鏈接對於類似的實現,輸入來自用戶[link](https://plnkr.co/edit/Bxfw6a?p=info)。有關管道的更多信息,請查看此[鏈接](https://rahulrsingh09.github.io/AngularConcepts/pipes) –

+0

謝謝,這可能非常有用。 – Muirik

回答

3

這不是使用管道過濾是一個好主意。在這裏看到的鏈接:https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

相反,在您的組件代碼添加到您的執行篩選。然後使用你的ngFor過濾數據。

下面是一個例子。那麼你會在這個例子中使用ngFor通過filteredProducts。

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); 
    } 
} 
1

您可以創建一個custom pipe了一個篩選項目時ü迴路循環。

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({name: 'notCompleted'}) 
export class notCompletedPipe implements PipeTransform { 
    transform(value: string]): string { 
    return value != 'completed'; 
    } 
} 

,並在這樣的HTML使用它,

<ng-template *ngFor="let flag['completed === false'] of service.flags | notCompleted"> 
    <span class="standard-flag" 
     [class.hold-flag]="flag?.flagType === 'hold'">Flag 
    </span> 
</ng-template>