【问题标题】:Unable to focus input field in ionic2无法在ionic2中聚焦输入字段
【发布时间】:2018-05-18 12:06:41
【问题描述】:

在我的 sn-p 中,我尝试为第一个输入文本字段设置焦点。但是当页面加载时,它会聚焦并突然失去焦点并关闭键盘。 谁能告诉我实现这一目标。

<ion-input [(ngModel)]="username" name="username" type="text" #username="ngModel" spellcheck="false" autocapitalize="off" autofocus clearInput required></ion-input>

【问题讨论】:

    标签: angular ionic2 autofocus


    【解决方案1】:

    在您的 html 中添加带有 (#) 的视图引用,

    <ion-input [(ngModel)]="username" name="username" type="text" #username="ngModel" spellcheck="false" autocapitalize="off" autofocus clearInput required  #focusInput></ion-input>
    

    在您的 component.ts 中导入 ViewChild 并设置 this(#focusInput) 输入的焦点

    喜欢

    import {Component, ViewChild} from '@angular/core';
    
    @ViewChild('focusInput') myInput;
    
    ionViewDidEnter() {
           this.myInput.setFocus();
        }
    

    这会有帮助。

    【讨论】:

    • 谢谢 Aneri。这对我不起作用。它显示与以前相同。它打开键盘并突然隐藏并失去焦点。
    【解决方案2】:
    <input #exampleInput />
    
    @ViewChild('exampleInput') exampleInput: ElementRef;
    
    setTimeout(() => {
        this.exampleInput.nativeElement.focus();
    }, 300);
    

    这对我有用。

    注意:您可能希望在ngAfterViewInit 方法或其他地方使用此超时,而300 毫秒延迟在我测试的设备中听起来足够了。

    【讨论】:

    • 谢谢希德。这对我不起作用。显示相同的屏幕。
    • 对不起希德。我只尝试了 300 毫秒。对于 300,它不起作用。超过 30000 可以正常工作,但有时无法正常工作。我试过 400 和 500,需要一些延迟才能集中注意力。有什么办法可以毫不拖延地做到这一点。
    • 我在emulator 也经历了不同的结果 | real device | --aot 标志正在使用中,所以对我来说 --aot 标志 + real device 组合工作正常。而且我还没有在旧手机中测试它,我怀疑与新手机(=更好的 CPU)相比可能效果不佳。不,我不知道没有使用超时的任何其他方式,如果你找到了,请告诉我! :^)
    • 无论如何感谢您的解决方案。我还有一个疑问。你能检查一下吗。 stackoverflow.com/questions/50460216/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多