0

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>

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I need to update it without using submit button. I don't need to reload the page.
It should like with the ajax, you type text and right away you have result
Then you can attach an event to your input, such as: <input (keyup)="filterByName($event.target.value)"> and remove your button, your function will now be filterByName(input) and you will use input variable instead of this.input
it doesn't work properly, if I type something it can find it but if I remove text and type something again it doesn;'t show me anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.