离子搜索栏中的明文

问题描述 投票:3回答:5

我有一个搜索栏

<div id="search"><ion-searchbar [(ngModel)]="searchQuery" (change)="onChange($event)" (ionClear)="onCancel($event)" (ionInput)="onInput($event)" debounce="1"></ion-searchbar></div>

我如何从ts文件中清除用户输入的文本?

这是尝试清除搜索栏文本的ts文件函数。

.
private searchQuery: string = null;
.

  subscribeEvents() {
    this.events.subscribe('mapFilter:update', (data) => {
      this.employeeModel = data[0].employeeModel;
      if (data[0].fromClearFilters) {
        this.searchQuery = '';
      }
      this.getMarkers();
      this.getPosition();
    });
  }

this.searchQuery = '';确实重置了过滤器,但文本仍然存在

谢谢

我正在使用Ionic 2

javascript html angularjs ionic-framework ionic2
5个回答
5
投票

首先,为HTML元素添加标识符

<ion-searchbar #mySearchbar ...>

然后,导入ViewChild:

import { ViewChild } from '@angular/core';

然后,导入搜索栏

import { Searchbar } from 'ionic-angular';

将其添加为属性:

@ViewChild('mySearchbar') searchbar: Searchbar;

然后,触发onInput事件并传递一个空标识符(这样你的onInput事件监听器就知道你了)

this.searchbar.clearInput(null);


1
投票

您可以使用发送的事件来获取如下所示的值,而不是在搜索栏中使用ngModel

<ion-searchbar (ionInput)="getItems($event)" (ionCancel)="onCancel($event)" [showCancelButton]="true"></ion-searchbar>

通过这样做,你可以通过以下方式清除(ionCancel)事件中的文本:

  onCancel(ev) { 
    // Reset the field
    ev.target.value = '';
  }

请注意,您不需要ngModel绑定,也不需要使用(change)="..."事件。


1
投票

任何有兴趣的人,这对我有用的方式是:

@ViewChild('userSearchBar') searchbar: Searchbar;

然后在你的方法:

this.searchbar._value='';

这就像一个魅力......


0
投票

你在使用Angular,不是吗?

所以你只需要在控制器中清除相关的模型“searchQuery”。这样,角度将自动清除场;

this.searchQuery = '';

但是ng-model应该绑定到一个对象而不是一个变量。

意味着变量的声明应该是这样的:

 $scope.searchBox = {
    searchQuery: ''
 };

并将搜索对象更改为:

<ion-searchbar ... ng-model="searchBox.searchQuery" ... />

0
投票

我的答案建立在DJ给出的答案之上。我只是回答他的回答,但我没有足够的声誉。所以,我会回答我自己的问题。

为了使clearInput()函数起作用。您需要将它传递给事件实例。

获得此功能的最佳方法是存储将函数与输出事件关联时传入的事件对象,如(ionInput)="myfunction($event)"。然后将其传递给clearInput函数。如果你输入null,它将返回像Cannot find property 'target' of null这样的错误。

例:

myFunction(event) {
    this.eventInstance = event;

    //the rest of your code
}
© www.soinside.com 2019 - 2024. All rights reserved.