In this demo, we will create an angular2+ versions app in which we will have live search. Search is one of the most important part of any web app, which makes the app more user friendly when we have lots of the data in the application.
So lets start with step by step:
create a new app by typing below command:
ng new search-angular
By typing above command over terminal a very basic app will be created so now type cd search-angular/ and type npm start or ng serve. Now go to your browser and type http://localhost:4200. Page will show like below.
In the folder src/app we have below files
app -- app.component.css -- app.component.html -- app.component.spec.ts -- app.component.ts -- app.module.ts
Now We will add a new file filter.pipe.ts
which will
hold our filter code.
Now we will create some static data in our ts file to apply filter on that, let's have a look in the file app.component.ts.
Now lets modify app.component.html
to display the users in a list. Add this to the html file:
Let’s populate the pipe with code for the filter. Copy and paste the below code into filter.pipe.ts
:
This code will return a subset of an array of items
if any item contains the searchText
string. In the above file we can see the searched columns key name has been separated with and so that filter can work on all the available columns, So columns can be there accordingly within this file.
we’ll need to import the Forms Module into the app module. To do this add the following import statement at the top of app.module.ts
: import { FormsModule } from '@angular/forms';
. We also need to import it in the NgModule decorator, so add it to the array of imports, after the BrowserModule.
app.module.ts
file should now look like this:
Now we use the filter pipe in our App Component. Let’s modify app.component.html
so that we have an input box where we can put our searchText
and let’s modify the list so that it makes use of our filter.
Your app.component.html
should now look like this:
Now look at app. You should see search box at top.
Type some text into the box and see that your list being dynamically filtered!
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.
Thanks!!