Set focus on an input with Ionic 2

后端 未结 10 2047
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 00:29

SOLVED :

import { Component, ViewChild} from \'@angular/core\';
import { Keyboard } from \'ionic-native\';


@Component({
  templateUrl: \         


        
10条回答
  •  不思量自难忘°
    2020-12-14 00:59

    None of the above was working for me. Here is how I resolved:

    import {  ElementRef, AfterViewChecked, Directive } from '@angular/core';
    import {Keyboard} from 'ionic-native';
    
    @Directive({
        selector: '[autofocus]'
    })
    export class FocusInput implements AfterViewChecked {
        private firstTime: boolean = true;
        constructor(public elem: ElementRef) {
    }
    
    ngAfterViewChecked() {
      if (this.firstTime) {
        let vm = this;
        setTimeout(function(){
    
        vm.elem.nativeElement.firstChild.focus();
        vm.firstTime = false;
        Keyboard.show();
    
        }, 300)
      }
     }
    }
    

    Then in your ion-input field just add the autofocus attribute:

     
    

    Tested on Browser and Android not IOS yet but no reason it should not work.

提交回复
热议问题