Angular2 – Dynamic Search Boxes

This particular recipe was taken from a course at Udemy:

https://www.udemy.com/angular-firebase-application

One of the most common examples given on Angular2 is to make a real time filtered list of notes or todo messages.

There’s many tutorials on this, including some at Udemy.

For my own benefit I’m documenting the process to help digest this.

In my test application, I have a value of lesson that is associated to the returned list of lessons from a database call.  Calling this in the view with an *ngFor tag to iterate over the lessons, gives me a nice list of data in the page.

But what if I want to have a field that when a user types into it, it filters the list to only display those results with matching content?

On the component that fuels this HTML, two variables will be used to replace the earlier one (lesson):

allLessons: Lesson[];

filtered: Lesson[];

In the Observable subscription call, it is modified from:

lessons => this.lesson = lesson

to become:

lessons => this.allLessons = this.filtered = lessons

In the HTML itself we would add an input tag like so:

<input class="search-bar" placeholder="Search" (keyup)="search(input.value)" #input>

Notice the action of keyup which is set to a search method.  We’re using a #input value in the tag and referencing that as what’s being passed into the search method call (input.value)  Basically what is being typed is taken and sent into the search method.

Back in the Component, we need to add a search method to support this HTML field:

search(search: string){
  this.filtered = this.allLessons.filter(lesson => lesson.description.includes(search));
}

…and that’s it.  At this point it works.

At this point, this is more of a recipe for me… I’m not sure I fully understand on a low level, what’s going on.  From a high level, I get it.  He’s creating a HTML input field and passing in input.value into this method.  This method is defining this.filtered as All the Lessons pulled from the database with a filter method applied.  The filter method is calling a function of lesson being equal to the lesson’s description, as long as the string passed in matches.

 

Angular2 – Dynamic Search Boxes
User Rating: 0 (0 votes)