angularangular7angular8devextremedevextreme-angular

How to set focus to dx-text-box?


I use dev extreme UI framework in Angular application.

In documentation I have found how to set focus it says to use method focus()

But there is not focus in DxTextBoxComponent

How to set focus?

My code is:

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

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

HTML is:

<dx-text-box #name>

No effect


Solution

  • Your code looks correct. Make sure that you imported all required dependencies and DxTextBoxComponent and there is only one TextBox with this identifier on the page. This code doesn't work in CodeSandbox (I believe this issue is specific to CodeSanbox), but it works in a local project and in DevExtreme Widget Gallery. Add the following code there

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

    I recorded a screencast.

    If the ViewChild directive doesn't work, you can get the component's instance using the onInitialized event handler:

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

    I also texted this approach locally and in their Widget Gallery. It doesn't require any additional imports and works fine.