2017-11-15 8 views
0

に資金を供給している私はこのようなJSONを持っている:角度2ストップ* NgForかの特定の値が

[ 
{"Name": "xxxx", "country": "country1", etc...} 
{"Name": "xxxx", "country": "country2", etc...} 
{"Name": "xxxx", "country": "country1", etc...} 
{"Name": "xxxx", "country": "country1", etc...} 
] 

...とコード:

<ng-container *ngFor="let contact of contacts"> 
    <ng-container *ngIf="contact.country == 'country1'"> 
    <div>COUNTRY1</div> 
</ng-container></ng-container> 

このコードはそれを見つけるたびにCOUNTRY1を作成します」 country1 " 国の値を一度印刷したいと思います。出来ますか?

+0

データを国別に別の配列にグループ化し、ビュー内でこの配列を反復処理することができます。 – Zabavsky

答えて

0

私はあなたのフィルタ基準と印刷フィルタリングされた結果に基づいて、あなたのリストをフィルタリングする最初の必要推測:

<ng-container *ngFor="let contact of contacts | filterBy: 'country1'"> 
    <ng-container ...> 
    <div>COUNTRY1</div> 
</ng-container></ng-container> 

、あなたはフィルタのパイプを作成する必要が

@Pipe({ 
    name: 'filterBy' 
}) 
export class FilterByPipe implements PipeTransform { 
    transform(value: any[], filter: string): any[] { 
    return value.filter(x => x.country === filter); 
    } 
} 
0

をフィルタリングするためにパイプを作成ユニークなアイテムの配列:

@Pipe({ 
    name: 'filterUnique', 
    pure: false 
}) 
export class FilterPipe implements PipeTransform { 

    transform(value: any, args?: any): any { 

    // Remove the duplicate elements 
    let uniqueArray = value.filter(function (el, index, array) { 
     return array.indexOf (el) == index; 
    }); 

    return uniqueArray; 
    } 
} 

パイプを適用することができます:

<ng-container *ngFor="let contact of contacts | filterUnique"> 
    <ng-container ...> 
    <div>COUNTRY1</div> 
</ng-container></ng-container> 

の作業例:次に

myList = [ 
{"Name": "xxxx", "country": "country1", etc...} 
{"Name": "xxxx", "country": "country2", etc...} 
{"Name": "xxxx", "country": "country1", etc...} 
{"Name": "xxxx", "country": "country1", etc...} 
]; 

myNewSet = Array.from(new Set(myList)); 

:あなたはその後、パイプを使用したくない場合はhttps://plnkr.co/edit/yxvoKVD3Nvgz0T3AB7w3?p=preview

OR

はあなたがすべての値のセットを使用することができますこのセットをテンプレートで使用します。