如何在用户点击搜索图标时在搜索栏上添加焦点并打开键盘?

时间:2018-01-02 20:01:55

标签: angular ionic-framework ionic2 ionic3

当我点击搜索图标时,它会打开栏上的搜索框,但我希望它能够专注于该字段并打开键盘。

我如何实现这一目标?

请在下面找到我的home.htmlhome.ts代码

home.html的

<ion-header>
  <ion-navbar color="primary">
    <button *ngIf="!toggled" ion-button icon-only menuToggle><ion-icon name="menu"></ion-icon></button>
    <!-- Title -->
    <ion-title *ngIf="!toggled">In&iacute;cio</ion-title>
    <!-- Search Bar -->
    <ion-searchbar *ngIf="toggled" [(ngModel)]="searchTerm" [showCancelButton]="true" (ionCancel)="toggleSearch()" (ionInput)="triggerInput($event)"></ion-searchbar>
    <!-- Search Icon -->    
    <ion-buttons end *ngIf="!toggled">
      <button ion-button icon-only (click)="toggleSearch()"><ion-icon name="search"></ion-icon></button>
    </ion-buttons>  
  </ion-navbar>
</ion-header>

<ion-content padding>

<ion-list>
  <ion-item *ngFor="let item of items">
    {{ item }}
  </ion-item>
</ion-list>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component( {
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    toggled: boolean;
    searchTerm: String = '';
    items: string[];

    constructor( public navCtrl: NavController, public navParams: NavParams ) {
        this.toggled = false;
        this.initializeItems();        
    }

    ionViewDidLoad() {
        console.log( 'ionViewDidLoad HomePage' );
    }

    toggleSearch() {
        this.toggled = this.toggled ? false : true;
    }

    initializeItems() {
        this.items = ['Amsterdam','Bogota','Mumbai','San José','Salvador']; 
     }    

    triggerInput( ev: any ) {
        // Reset items back to all of the items
        this.initializeItems();
        // set val to the value of the searchbar
        let val = ev.target.value;
        // if the value is an empty string don't filter the items
        if (val && val.trim() != '') {
          this.items = this.items.filter((item) => {
            return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
          })
        }  
    }
}

1 个答案:

答案 0 :(得分:2)

我解决了这个问题:

  1. 导入搜索栏 ViewChild
  2. 
        import { Searchbar } from 'ionic-angular';
        import { ViewChild  } from '@angular/core';
    
    
    1. 定义搜索栏:
    2.     export class HomePage {
      
              @ViewChild('searchbar') searchbar:Searchbar;
      
              ... some code
      
          }
      
      
      1. 专注于他:
      2. 
            toggleSearch() {
                setTimeout(() => {  
                    this.searchbar.setFocus();
                }, 5);
            }
        
        
        1. 在HTML中添加 #searchbar 标记,如下所示:

          <ion-searchbar #searchbar ...some code...></ion-searchbar>

        2. 请参阅离子论坛上的more