Ok First of all never user Pipes to filter or order any array or others objects that you have. If you are from Brazil just watch this class:
https://www.youtube.com/watch?v=h1t_O_w0LOc&list=PLGxZ4Rq3BOBoSRcKWEdQACbUCNWLczg2G&index=49
This girl explain why you should never filter or order anything with pipes.
Ok now let's create the correct input with autocomplete and at the same time filter the user input value.
At this example user will search one book of our books array.
This is the component:
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'app-filter-examples',
templateUrl: './filter-examples.component.html',
styleUrls: ['./filter-examples.component.css']
})
export class FilterExamplesComponent implements OnInit {
books: string[] = ['Angular JS', 'Angular 2', 'JavaScript', 'HTML 5 and CSS 3',
'Java 1', 'Java 2', 'Java 3', 'php', 'Typescript', 'C', 'c++',
'C#'];
filtro: string = '';
getBooks() {
// if the input is empty search result will show 0 books.
//This is just to not show all books before user do any search
if (this.filtro === '') {
return null;
}
if (this.books.length === 0 || this.filtro === undefined) {
return this.books;
}
// Here where we will do the search. First of all filtro(filter in portuguese)
// will be compare to all elements in our books (all of then in lower case)
// and will return all the elements that match with the variable filtro
return this.books.filter((v) => {
if (v.toLowerCase().indexOf(this.filtro.toLowerCase()) >= 0) {
return true;
}
return false;
});
}
}
Now this is our html file:
<html>
<body>
Search some Book <br>
<input list="testAutocomplete" [(ngModel)]="filtro" >
<datalist id="testAutocomplete">
<option *ngFor="let book of books">
{{ book }}
</option>
</datalist>
<h1> Search Result </h1>
<ul>
<li *ngFor="let book of getBooks()">
{{ book }}
</li>
</ul>
</body>
</html>
The best way to do a simple search with autocomplete in Angular 2 is using datalist tag and ngFor to list the options. It's really simple. And don't forget the ngModel as input attribute to use this value in our methods in component.
OBS: the method getBooks is only to display the result to user in a dynamic list.