简体   繁体   中英

(Angular2) `*ngfor` doesn't work with filter using pipe from async data

I have simple Angular 2 app as below:

Data structure

class Item {
  name: string,
  status: boolean
}

Template

<ul *ngIf="items">
  <li *ngFor="let item of items">{{ item.name }}</li>
</ul>

Component

export class ItemsComponent implement OnInit {

  items: Item[]

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.getItems();
  }

  private getItems(): void {
    this.itemService.getItems().then(items => this.items = items);
  }

}

with asynchronous data receiver getItems() of ItemService which uses Promise .

This app works great. The full item list is shown on the browser.


I want to display only the items with status true . To do this, I implemented a simple pipe to filter items by status :

@Pipe({
  name: 'filterByStatus'
})
export class FilterByStatusPipe implements PipeTransform {

  transform(votes: Vote[], status: boolean): Vote[] {
    return votes.filter(vote => vote.status === status);
  }
}

and I updated li tag in my template as

<li *ngFor="let item of items|filterByStatus:true">{{ item.name }}</li>

But, this update makes <ul *ngIf="items"> false so <li> s are not computed. (ie items === undefined )

I don't know why first version works well but updated version does not. And how can I get items with status === true ?

Thanks.

Everybody should know:

DON'T use status for the name of your properties or variables. It would be potentially used in your environment.

See this: JS reserved keywords list


Renaming solves the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM