0

I'm a new developper in angular 2 and I really really got difficulties with it...

I have a simple array of json objects that I want to filter to search elements depending on some values. For example, I have this array :

invoiceList = 
  [
    {
      invoiceNumber: 1234, 
      invoiceSupplier: "test", 
      invoiceStatus: "Import error", 
      invoiceCategory: "invoice with GR", 
      date: "22/01/2017", 
      amount : 134527
    },
     //others elemenys...
  ];

And I want to filter elements that have depending on the name AND the status AND the amount for example. I know that in Angular 1 we can use filters and it was easier and clearer for me, but I saw that they were removed in Angular2 and I was really really consufed about the pipes that they introduced.

Can you please show me how can I filter that array in .ts part and the .html part? Please because I felt that I'm really blocked...

Thanks in advance !

1
  • You can use pipes in angular 2 for filtering Commented Jan 24, 2017 at 11:32

1 Answer 1

1

You can use pipes in angular 2, something like

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
    name: 'isInRole',
    pure: false
})
export class IsInRole implements PipeTransform {
    transform(roles: string[], roleName: string): boolean {
        let filteredRoles = roles.filter(p => p.indexOf(roleName) !== -1);
        if (filteredRoles.length > 0)
            return true;
        return false;
    }
}

In your app.module.ts, register this like

import {IsInRole} from './pipes/isinrole.pipe';

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [IsInRole],
    bootstrap: [AppComponent]
})
export class AppModule { }

and then use it like this in your template

<div class="col-md-6" *ngIf="(roles | isInRole: 'Administrator')">
    ...
</div>
Sign up to request clarification or add additional context in comments.

6 Comments

I have just two question please : doest it works if I want to do an AND search? I mean if I want to search at three values (amount, date and number for example). Can you show me the html code please? thank you !
I have added html code for how to use it. Its similar to what filters used to be in angular 1. And yes you can pass multiple parameters to your pipe similar to how we used to do in angular 1.
{{ collection | pipeName: arg1:arg2:arg3... }}
Sorry but it's still not very clear to me. Sorry. (I'm a newbiein programming even in angular1 and it's worse in angular2...). Here is a plunker of my two files : plnkr.co/edit/vS0SBYgiuhrFub1zfczS I hope you can understand what I want to do. It's just a simple search depending on four values (the buttons) but I really don't know how to do that specifically....
up please... :(
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.