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

问题描述 投票:-1回答:1

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

我该如何实现这一目标?

请在下面找到我的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);
          })
        }  
    }
}
angular ionic-framework ionic2 ionic3
1个回答
2
投票

我解决了这个问题:

  1. 导入搜索栏和ViewChild:

    import { Searchbar } from 'ionic-angular';
    import { ViewChild  } from '@angular/core';

  1. 定义搜索栏:
    export class HomePage {

        @ViewChild('searchbar') searchbar:Searchbar;

        ... some code

    }

  1. 并集中关注他:

    toggleSearch() {
        setTimeout(() => {  
            this.searchbar.setFocus();
        }, 5);
    }

  1. 在HTML中添加#searchbar标志,如下所示: <ion-searchbar #searchbar ...some code...></ion-searchbar>

请参阅离子论坛上的more

© www.soinside.com 2019 - 2024. All rights reserved.