簡體   English   中英

使用可觀察的角度2的數組中的搜索元素

[英]search element in array using observable in angular 2

我有書名的搜索輸入,我需要它來查找書而無需重新加載頁面。 重新加載頁面時,我的代碼可以正常工作,我輸入書名並推送提交。

如何使用可觀察的方式重寫此代碼,從而在不重新加載頁面的情況下搜索書籍?

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>

您不需要為此使用可觀察對象,如果您在組件中更新了filteredItems變量,則該變量將在您的視圖中更新,例如:

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
  });
}

並且在您看來:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM