如何从离子搜索栏获取输入?

How to get input from ion-searchbar?

这是一个非常简单的问题,但我似乎无法弄清楚(是的,我已经阅读了文档)。

我试图让输入用户输入 ion-searchbar (在 Ionic v4 中) 在他们按下搜索并输入 const/let 之后.

麻 HTML

<ion-searchbar showCancelButton="focus" class=""></ion-searchbar>

我不知道应该如何为此编写 TS。

提前致谢:{)

始终阅读 API、插件或任何您正在寻找的文档。 您将使用 ionChange() or ionInput() 获取数据。 在 HTML 文件

中使用以下代码
<ion-searchbar 
  showCancelButton="focus"  
  ionInput="getData()" 
  class="">
</ion-searchbar>

在 TypeScript 中。

public getData(){ 
   //ur logic here
}  
  • 使用 (search) 事件来调用您的函数。当用户单击 ion-searchbar.

    提供的搜索按钮时会触发此事件
  • 要获取在搜索栏中输入的值,请使用 $event.target.value 获取标签的值字段,在本例中为 <ion-searchbar>

    <ion-searchbar
        showCancelButton 
        searchIcon="search" 
        animated
        cancel-button-icon
        (ionCancel)="hideSearch()"
        (search)="yourSearchFunction($event.target.value)" 
        placeholder="Search Some Values">
    </ion-searchbar>
    

收听用户在搜索栏中键入内容时的变化:

    <ion-searchbar
        ... 
        (ionInput)="yourInputChangeFunction($event.detail.value)">
    </ion-searchbar>

注意:在 Ionic 6+ 上,(ionInput) 奇怪地在 $event.target.value 上发出值,尽管他们的 documentation 提到了 $event.detail

在您的 .html 文件中:

<ion-searchbar
    [(ngModel)]="autocomplete.input"
    (ionInput)="updateSearchResults()"
    placeholder="Search for a place">
</ion-searchbar>

在您的 .ts 文件中:

export class LoginPage{

  autocomplete: { input: string; }; 

  updateSearchResults() {
     console.log(this.autocomplete.input)    //search input will display
  }
}

使用@ViewChild 指令获取对搜索栏的引用:

查看: <ion-searchbar #search></ion-searchbar>

组件: @ViewChild('search', {static: false}) search: IonSearchbar;

之后,获取ion-searchbar的值如下:

const input = await this.search.getInputElement(); const searchValue = input.value;

希望这有效。

Html 文件。

<ion-toolbar>
    <ion-searchbar 
       debounce="1000" 
       (ionChange)="ionChange($event)">
    </ion-searchbar>
</ion-toolbar>

ts 文件

ionChange(event) {
    console.log(event.detail.value)
}