1

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

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

但是没有重点DxTextBoxComponent

如何设置焦点?

我的代码是:

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

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

HTML是:

<dx-text-box #name>

没有效果

4

4 回答 4

4

您的代码看起来正确。确保您导入了所有必需的依赖项和 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();
    }
}

我录制了一个截屏视频

如果 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 中给这种方法发了短信。它不需要任何额外的导入并且工作正常。

于 2019-11-29T10:41:08.320 回答
2

你错过了一个实例。DxTextBoxComponent 的实例是 dxTextBox,它的实例有 focus() 方法。

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

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

于 2020-03-27T08:39:51.900 回答
0

你可以这样尝试

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>
于 2019-11-28T11:49:11.183 回答
0

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

let theInstance;
const getInstance = (e) => {
    theInstance = e.component;
}
const someFunction = () => {
    theInstance.focus(); 
}
<TextBox onInitialized={e => getInstance(e)} />
于 2021-03-11T15:33:37.513 回答