【问题标题】:How to set focus to dx-text-box?如何将焦点设置到 dx-text-box?
【发布时间】:2020-03-24 01:25:21
【问题描述】:

我在 Angular 应用程序中使用dev extreme UI 框架。

在文档中我找到了如何设置 focus 它说要使用 method focus()

但是DxTextBoxComponent没有焦点

如何设置焦点?

我的代码是:

@ViewChild("name", { static: false }) public inputName: DxTextBoxComponent;

  ngAfterViewInit() {
    this.inputName.instance.focus();
  }

HTML 是:

<dx-text-box #name>

没有影响

【问题讨论】:

  • 将 html 标记引用到 ViewChild(即:yourTextbox)。然后,当您想集中注意力时,只需使用 this.yourTextbox.instance.focus();
  • 方法focus()Methods部分中
  • 您必须“获取实例”然后调用this.myWidget.instance.focus(),其中myWidget 是通过@ViewChild() 装饰器访问的。所以这不是一个真正的 Angular 组件。它只是一个包装器,您可以访问属性instance 来获取内部小部件,顺便说一下,单词 widget 指的是 jQuery 小部件。糟糕!

标签: angular angular7 angular8 devextreme devextreme-angular


【解决方案1】:

您的代码看起来正确。确保您导入了所有必需的依赖项和 DxTextBoxComponent,并且页面上只有一个具有此标识符的 TextBox。这段代码在 CodeSandbox 中不起作用(我相信这个问题是 CodeSanbox 特有的),但它在本地项目和 DevExtreme Widget Gallery 中起作用。在此处添加以下代码

app.component.html

<dx-text-box #name value="John Smith"></dx-text-box>

app.component.ts

//additional imports
import { ViewChild } from '@angular/core';
import { DxTextBoxComponent } from 'devextreme-angular';

//replace the AppComponent with this code
export class AppComponent {
    @ViewChild("name", { static: false }) inputName: DxTextBoxComponent;
    
    ngAfterViewInit() {
        this.inputName.instance.focus();
    }
}

我录制了screencast

如果 ViewChild 指令不起作用,您可以使用 onInitialized 事件处理程序获取组件的实例:

app.component.html

<dx-text-box #name (onInitialized)="getInstance($event)"></dx-text-box>

app.component.ts

export class AppComponent {
   inputName: any;

   getInstance(e) {
      this.inputName = e.component;
   }

   ngAfterViewInit() {
      this.inputName.focus();
   }
}

我还在本地和他们的 Widget Gallery 中给这种方法发了短信。它不需要任何额外的导入并且工作正常。

【讨论】:

  • 输入名称中没有.focus();,它不起作用
【解决方案2】:

您缺少一个实例。 DxTextBoxComponent的实例是dxTextBox,它的实例有focus()方法。

ngAfterViewInit() {
    this.inputName.instance.instance.focus();
  }

缺点是 Angular 编译器根本不喜欢这个,所以如果你找到解决方法,请回复我:p

【讨论】:

    【解决方案3】:

    你可以这样试试

    TS

    @ViewChild('search', { static: false }) public searchTextBox: DxTextBoxComponent;
    
    someFunction() {
    this.searchTextBox.instance.focus();
    }
    

    HTML

    <dx-text-box  #search>
    </dx-text-box>
    
    <button (click)="someFunction()"></button>
    

    【讨论】:

    • 不行,看看这个,我试过这个解决方案,@ViewChild没有实例
    • 你有没有尝试将focus() 放入超时时间,像这样setTimeOut(resp =&gt; { this.searchTextBox.instance.focus(); }, 0)
    • bcs 在我的情况下它按预期工作而没有使用超时
    【解决方案4】:

    以防万一。 这是 React 的工作代码:

    let theInstance;
    const getInstance = (e) => {
        theInstance = e.component;
    }
    const someFunction = () => {
        theInstance.focus(); 
    }
    <TextBox onInitialized={e => getInstance(e)} />
    

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多