【问题标题】:Angular custom focus directive not working on ion-item (but does work on the native <input/>)Angular 自定义焦点指令不适用于 ion-item(但适用于原生 <input/>)
【发布时间】:2019-01-23 07:09:42
【问题描述】:

我有以下指令:

import {Directive, ElementRef, Input, OnChanges, OnDestroy, Optional} from '@angular/core';

@Directive({
    selector: '[appFocus]',
})
export class AppFocusDirective implements OnChanges {
    @Input() appFocus: boolean = false;
    @Input() focusDelay: number = 0;

    constructor(private elementRef: ElementRef) {}
    ngAfterViewChecked(){
      this.checkFocus();
    }

    private checkFocus() {
        if (this.appFocus && document.activeElement !== this.elementRef.nativeElement) {
            let checkFocusTimeoutHandle: number;
            const focus = () => {
                this.elementRef.nativeElement.focus();
            };
            checkFocusTimeoutHandle = setTimeout(focus, this.focusDelay) as any;
        }
    }
}

其目的是在视图初始化后将焦点设置在元素上。我正在使用 ionic 构建我的应用程序,我需要对离子输入组件使用这种效果,但它似乎不起作用。但是,当我在本机输入元素上使用此指令时,它确实有效。

  <!--doesn't get focused (when uncommented)-->
  <!--<ion-input [appFocus]="true" ></ion-input>-->
  <!--does get focused-->
  <input [appFocus]="true" /> 

我必须改变什么才能使这项工作适用于 ion-item?

这是带有演示的STACKBLITZ。要使 focus() 效果起作用,必须通过其 DIRECT LINK 查看 stackblitz 应用程序。

【问题讨论】:

  • stackblitz 正在工作!
  • 本机输入有效。如果您注释掉本机输入并取消注释 ion-input - 您会看到问题。
  • 你想要达到的目标在 iOS 设备上是行不通的——苹果的立场是只有用户应该“创造”焦点。至少在现代 iOS Safari 中(10,3 左右之后)它现在不能通过 js 触发
  • @SergeyRudenko 感谢您的提醒!

标签: javascript html angular ionic-framework ionic3


【解决方案1】:

如果您想以编程方式使用模板 ref 设置 ion-item 焦点或使用 ViewChild 从 dom 获取 ref

HTML

 <ion-input  #ref type="text" formControlName="x"></ion-input>
   </ion-item>

TS

 @ViewChild('ref') ref:Elementef;

 onFocus(){      
   //set autofocus when click the button
     this.ref['_native'].nativeElement.focus();
  }

其他明智的使用自动对焦属性

<ion-input autofocus="true" name="title"></ion-input>

例如:https://stackblitz.com/edit/ionic-ewuvzq

【讨论】:

  • stackblitz 不起作用。这两个建议都试过了,但都不起作用
  • 它工作正常检查。如果您单击按钮,它将自动聚焦输入元素
  • 我的意思是 stackblitz 没有加载。它永远显示“正在启动开发服务器”。
  • 尝试在其他浏览器中打开
  • 好的,stackblitz 现在可以工作了。但是有不同的用例。我有一个输入列表。我有一个按钮,可以将一个项目添加到我的模型中。新添加的项目导致另一个列表项目 - 这是我必须关注的项目。请参阅此堆栈闪电战:stackblitz.com/edit/ionic-bcm84s?file=pages/home/home.html
【解决方案2】:

或者你可以使用 autofocus 原生属性,就像这样。

<ion-input autofocus="true" name="title"></ion-input>

【讨论】:

  • 不幸的是,这行不通。我创建了能够绑定焦点的指令。绑定 [autofocus] 时,焦点丢失或不存在。
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多