Le Dinh Nhat Khanh Le Dinh Nhat Khanh - 1 year ago 184
TypeScript Question

Filter object array with pipe Angular 2

I have a class:

export class Todo {
public id: number;
public name: string;
public isCompleted: boolean;
public dateCreated: Date;
public userName: string;

A service:

getTodos (): Observable<Todo[]> {
return this.http.get(this.todosUrl)

private extractData(res: Response) {
let body = res.json();
return body || { };

In my component:

todos => this.todos = todos,
error => this.errorMessage = <any>error

And html file:

<div class="ui large selection animated divided list">
<a *ngFor="let todo of (todos | todoFilter:false)" class="item">
<div class="right floated content">
<div class="ui vertical animated negative button" tabindex="0">
<div class="hidden content">Delete</div>
<div class="visible content">
<i class="fa fa-trash" aria-hidden="true"></i>
<i class="minus square outline icon"></i>
<div class="content">
<div class="header">{{todo.name}}</div>
<div class="description">{{todo.dateCreated | date:"MMM-dd-yyyy"}}</div>

The problem is, when I try to use this pipe to filter the completed todos, I keep getting an error that say Cannot read property 'filter' of undefined. Did I do something wrong or are there any ways to filter it without using an pipe?
My pipe:

transform(allTodos: Todo[], args?: boolean){
if (allTodos === null) {
return null;
return allTodos.filter(todo => todo.isCompleted);

Thank you.

Answer Source

Try to replace the if (allTodos === null) to just if (!allTodos) I think the problem is that you're getting to the .filter even while your this.todos is still empty since you're only checking that it isn't null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download