当用户在 Ionic 中的搜索栏外单击时无法隐藏搜索

Not able to hide the search when the user clicks outside of search bar in Ionic

我在我的 Ionic 应用程序中工作,我在我的 Ionic 应用程序中添加了一个搜索栏,但问题是当我在搜索结果之外单击时,搜索栏应该隐藏但它没有隐藏,结果是也在那里。

我希望当用户在搜索栏外单击时,它应该隐藏搜索栏并且还应该清除结果。

这是我的app.html:

  <ion-navbar>
    <button ion-button menuToggle start>
      <ion-icon name="menu"></ion-icon>
    </button>
    <div class="mydiv2">
      <ion-icon name="search" class="myicon22" (click)="hasSearchnot()"></ion-icon>
    </div>
  </ion-navbar>
  <ion-searchbar *ngIf="HasSearch" (input)="setSearchProducts($event)"></ion-searchbar>
  <ion-list *ngIf="HasSearch">
    <ion-item *ngFor="let item of finalproductsearch" (click)="showProductDetails(item)">
      <ion-thumbnail item-start>
        <img src="{{'images.pro_images}}">
      </ion-thumbnail>
      {{ item.product_name }}
    </ion-item>
  </ion-list>

在此视图中,我有一个搜索图标,当用户单击搜索图标时,搜索栏将打开。

这是我的app.component.ts:

HasSearch: boolean;
hasSearchnot()
{
    this.HasSearch = !this.HasSearch;
}

getsearchproducts()
{
    this.restProvider.getproductsforsearch()
      .then(data => {
      this.searchproduct = data;
      this.finalseaproduct = this.searchproduct.msg;
      });
}

我的搜索结果显示正常,但问题是当我点击搜索结果以外的地方时,它应该关闭搜索栏并清除搜索结果,但这并没有发生。

当我转到下一页时,之前的搜索结果仍然存在。我想在用户移动到下一页时清除搜索结果。

非常感谢任何帮助。

此代码可根据您的要求正常运行,试试这个:

app.html:

<ion-navbar (click)="hideSearchbar($event)" >
  <button ion-button menuToggle start>
    <ion-icon name="menu"></ion-icon>
  </button>
  <div class="mydiv2">
    <ion-icon name="search" class="myicon22" (click)="hasSearchnot($event)"></ion-icon>
  </div>
</ion-navbar>
<ion-searchbar *ngIf="HasSearch" (input)="setSearchProducts($event)"></ion-searchbar>
<ion-content  (click)="hideSearchbar($event)">
<ion-list *ngIf="HasSearch">
  <ion-item *ngFor="let item of finalproductsearch" (click)="showProductDetails(item)">
    <ion-thumbnail item-start>
      <img src="{{'images.pro_images}}">
    </ion-thumbnail>
    {{ item.product_name }}
  </ion-item>
</ion-list>
</ion-content>

app.component.ts:

HasSearch: boolean;
  hasSearchnot(e) {
    console.log("hasearch searchbar", this.HasSearch);

    if(e.target.classList.contains('myicon22')){
          this.finalsearchproduct = " ";    
      this.HasSearch = !this.HasSearch;

    }
  }
  hideSearchbar(e) {
    if(!e.target.classList.contains('myicon22')){

    if (this.HasSearch == true) {
      this.HasSearch = false;
      this.finalsearchproduct = " ";
    }
  }
  }
  getSearchProducts() {
    this.restProvider.getproductsforsearch()
      .then(data => {
      this.searchproduct = data;
      this.finalseaproduct = this.searchproduct.msg;
      });
  }

这里我使用了 e.target.classList.contains('myicon22') 这将 return 真或假根据特定标签有 "myicon22" 作为 child class 或不作为,并且通过使用该逻辑,我们可以在用户单击搜索栏之外的某个位置时隐藏搜索栏。

谢谢。