Angular 2:* ngFor内变量的范围

时间:2017-04-18 14:58:32

标签: angular

是否可以从项目列表获取"项目" 并转移到项目过滤器并使用它在组件内部如使用服务?

<div class="container">
    <item-filter (testOut) = "retrieveMe($event)" ></item-filter>
    <div class="row">
    <item-list *ngFor = "let item of items | filter :   filterConditions" [storyInfo] = 'item'></item-list> 
    </div><!-- Row -->
</div><!-- Container-->

1 个答案:

答案 0 :(得分:1)

将部分从管道移动到父组件,包括已过滤列表的属性以及列入项目过滤器的@Input

父组件类:

items: any[] = [];
filteredItems: any[] = [];

retrieveMe(criteria: any): void {
  this.filteredItems = this.filter(items, criteria);
}

filter(items: any[], criteria: any): any[] {
  return // code from your pipe (input and output would be the same)
}

父模板:

<div class="container">
  <item-filter (testOut)="retrieveMe($event)" [filteredItems]="filteredItems"></item-filter>
  <div class="row">
    <item-list *ngFor = "let item of filteredItems" [storyInfo] = 'item'></item-list> 
  </div><!-- Row -->
</div><!-- Container-->

item-filter组件类:

import { ..., Input } from '@angular/core';

@Input() filteredItems: any[] // <- here's your filtered items list