【问题标题】:Set focus on an input with Ionic 2使用 Ionic 2 将焦点设置在输入上
【发布时间】:2017-01-29 11:22:18
【问题描述】:

已解决:

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


@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput ;

  constructor() {}

  ionViewDidLoad() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150);

 }

} 

1) 导入“ViewChild”

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

2) 在您的 html 模板中创建对您的输入的引用:

<ion-input #focusInput></ion-input>

3) 使用@ViewChild 访问您刚才引用的输入组件。

@ViewChild('focusInput') myInput ;

4) 触发焦点

每次加载视图/页面时使用 ionViewLoaded() 方法触发它。

需要setTimeout

  ionViewLoaded() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150); //a least 150ms.

 }

4) 在 Android 上显示键盘

import { Keyboard } from 'ionic-native';

调用 Keyboard.show() 在 Android 上调用键盘。

5) 在 iOS 上显示键盘

将此行添加到您的 config.xml 以使其在 iOS 上运行:

&lt;preference name="KeyboardDisplayRequiresUserAction" value="false" /&gt;

在 mhartington 伟大文章的帮助下:http://mhartington.io/post/setting-input-focus/

【问题讨论】:

  • 它在 iOS 中不起作用 :(
  • ionViewLoaded() 对我不起作用,我不得不使用ionViewDidLoad()
  • 另外,如果您使用ionic serve 进行测试,我相信会看到类似“Native:尝试调用 Keyboard.show,但 Cordova 不可用”的内容。确保在控制台中包含 cordova.js 或在设备/模拟器中运行意味着它可以工作。
  • 当我这样做时,我得到“ngc:错误:无法分配给引用或变量!”建设时
  • 您可以使用“发布您的答案”按钮将问题转换为新答案吗?将答案放在问题主体中令人困惑,当我发现您的问题时,我无法理解答案在哪里。将新的答案标记为正确后,它将帮助人们更好地指导自己:)

标签: input focus ionic2 setfocus autofocus


【解决方案1】:

您不需要从“angular/core”导入“输入”。

简单地说:

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

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput: TextInput;

  constructor(private navCtrl: NavController) { }

  ionViewDidLoad() {

    setTimeout(() => {
      this.myInput.setFocus();
    },150);

 }

} 

并回答 Ciprian Mocanu 的评论:

它在 iOS 中不起作用:(

它适用于 iOS -> 在带有 iOS 10 的 iPhone 6 PLUS 上检查

【讨论】:

  • 实际上,如果您使用 WKWebView,它将无法在 iOS 上运行,如本 Cordova 问题中所述:issues.apache.org/jira/browse/CB-10376。不过,提供的修复确实适用于 UIWebView。
  • 这适用于 iPhone 6S 上的 iOS 11.3.1,使用 WKWebView 和 ionic-angular 3.9.2。
【解决方案2】:

我认为你应该为此制定一个全局指令,因为你可能不止一次想要这种行为。

import {  ViewChild, ElementRef, Directive, OnInit } from '@angular/core';
import { Keyboard } from 'ionic-native';

@Directive({
    selector: '[autofocus]'
})
export class FocusInput implements OnInit {
    @ViewChild('myinput') input
    private focused: boolean
    ngOnInit(){
      this.focused = true
    }
    ionViewDidLoad() {
      if (this.focused) {
        setTimeout(()=>{
          this.input.setFocus()
          this.focused = false
          Keyboard.show()
        }, 300)
      }
    }
}

现在在 ion-input 字段中添加 autofocus 属性

<ion-input #myinput type="..." placeholder="..."
            (keyup.enter)="someAction()"
            autofocus ></ion-input>

【讨论】:

  • ionViewDidLoad 未触发。这是离子输入控件的正确事件吗?
  • ionViewDidLoad 和 viewchild 在指令下都不起作用
【解决方案3】:

以上都不适合我。以下是我的解决方法:

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)
  }
 }
}

然后在您的 ion-input 字段中添加 autofocus 属性:

 <ion-input #input type="text" placeholder="..."
            [(ngModel)]="myBoundVariable"
            (keyup.enter)="myEnterKeyAction()"
            autofocus></ion-input>

在浏览器和 Android 上测试,但尚未在 IOS 上测试,但没有理由不应该工作。

【讨论】:

    【解决方案4】:

    import {Component, ViewChild} from '@angular/core';
    import {NavController} from 'ionic-angular';
    
    @Component({
      templateUrl: 'build/pages/home/home.html'
    })
    export class HomePage {
      @ViewChild('Comment') myInput ;
    
      constructor(private navCtrl: NavController) { }
    
      ionViewLoaded() {
    
        setTimeout(() => {
          this.myInput.setFocus();
        },150);
    
     }
    
    }

    Create a reference to your input in your template :
    
    <ion-input #Comment>

    【讨论】:

    • 为什么是 150 英里秒?
    【解决方案5】:
    import {Component,ViewChild} from '@angular/core';
    import {NavController} from 'ionic-angular';
    
    @Component({
      templateUrl: 'build/pages/home/home.html'
    })
    export class HomePage {
      @ViewChild('myInput') myInput ;
    
      constructor(private navCtrl: NavController) { }
    
      ionViewDidLoad() {
    
        window.setTimeout(() => {
          this.myInput.setFocus();
        }, 600); //SET A LONG TIME IF YOUR ARE IN A MODAL/ALERT
    
      }
    
    }
    
    <ion-input #myInput ></ion-input>
    

    【讨论】:

      【解决方案6】:

      如果您需要在 init 组件中设置输入焦点,请将类 input-has-focus 默认设置为 ion-item,如下所示:

      <ion-item class="input-has-focus">
      

      就是这样!

      【讨论】:

        【解决方案7】:

        我发现这个解决方案也可以解决键盘将内容推开的问题。

        <ion-list>
        <ion-item>
          <ion-label>Name</ion-label>
          <ion-input #inputRef type="text"></ion-input>
        </ion-item>
        <button ion-button (click)="focusMyInput(inputRef)">Focus</button>
        

          @ViewChild(Content) content: Content;
        
          focusMyInput(inputRef) {
            const itemTop = inputRef._elementRef.nativeElement.getBoundingClientRect().top;
            const itemPositionY = this.content.scrollTop + itemTop -80;
        
            this.content.scrollTo(null, itemPositionY, 500, () => {
              inputRef.setFocus();
            });
          }
        

        【讨论】:

          【解决方案8】:

          就我而言,由于某种原因,ionViewLoaded() 没有被触发。尝试了 ionViewDidLoad() 并将计时器设置为 200 并且它起作用了。

          150 对我来说太早了。完整的解决方案:

          import { Component, ViewChild } from '@angular/core';//No need to import Input
          
          export class HomePage {
          
            @ViewChild('inputToFocus') inputToFocus;
            constructor(public navCtrl: NavController) {}
          
            ionViewDidLoad()
            {
              setTimeout(() => {
                this.inputToFocus.setFocus();
              },200)
            }  
          }
          

          在输入标签上:

          <ion-input type="text" #inputToFocus></ion-input>
          

          【讨论】:

            【解决方案9】:

            对于 IOS 和 Android,它对我来说很好用。将焦点代码放在 ionViewWillEnter() 中。

            import { Component, ViewChild, ElementRef } from '@angular/core';
             import { Keyboard } from '@ionic-native/keyboard';
            @Component({
              selector: 'page-home',
              templateUrl: 'home.html'
            })
            export class HomePage {
             @ViewChild("Input") inputEl: ElementRef;
             constructor(public keyboard:Keyboard){}
            
             ionViewWillEnter() { 
                setTimeout(() => {           
                  this.inputEl.nativeElement.focus();
                  this.keyboard.show();    
                }, 800); //If its your first page then larger time required 
            }
            

            html文件中的输入标签

             <ion-input type="text" #Input></ion-input>
            

            并将这一行添加到您的 config.xml 以使其在 iOS 上运行:

            <preference name="KeyboardDisplayRequiresUserAction" value="false" />
            

            【讨论】:

              【解决方案10】:

              设置超时对我有用!

              setTimeout(() => {
                  this.inputToFocus.setFocus();
              }, 800); 
              

              但是,如果添加了新的输入元素,它会将焦点设置为仅第一个输入。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-05-15
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-08-31
                • 1970-01-01
                • 1970-01-01
                • 2012-06-18
                相关资源
                最近更新 更多