rick1
rick1

Reputation: 946

search element in array using observable in angular 2

I have search input for the book title and I need it to find books without reloading the page. My code works at the moment witht he reloading of the page, I type book name and push submit.

How can I rewrite this code in order to use observable, thus search for the books without reloading the page?

filterByName(){
    this.filteredItems = [];

    if(this.inputName != ""){
      this.books.forEach(element => {
        if(element.author.toUpperCase().indexOf(this.inputName.toUpperCase())>=0 ||
            element.title.toUpperCase().indexOf(this.inputName.toUpperCase())>=0){
          this.filteredItems.push(element);
        }
      });
    }else{
      this.filteredItems = this.books;
    }
    console.log(this.filteredItems);
    this.init();
  }

HTML:

<div class="form-group">
    <label>Filter </label>
    <input  type="text"  id="inputName" [(ngModel)]="inputName"/>
    <input type="button" (click)="filterByName()" value="Apply"/>
  </div>

Upvotes: 0

Views: 168

Answers (1)

rbaumier
rbaumier

Reputation: 594

You don't need to use observables for that, if you update your filteredItems variable in your component, it'll be updated in your view, such as:

filterByName() {
  if(this.inputName.length < 1) {
    return;
  }
  this.filteredItems = this.books.filter(book => {
    return book.author.toUpperCase().indexOf(this.inputName.toUpperCase()) >= 0 ||
      book.title.toUpperCase().indexOf(this.inputName.toUpperCase()) >= 0
  });
}

and in your view:

<div class="form-group">
  <label>Filter </label>
  <input  type="text"  id="inputName" [(ngModel)]="inputName"/>
  <input type="button" (click)="filterByName()" value="Apply"/>
</div>

<ul>
  <li *ngFor="let book in filteredBooks">{{ book.title }} - {{ book.author }}</li>
</ul>

Upvotes: 1

Related Questions