打开剑道窗口时在文本框中设置焦点

时间:2018-07-27 14:53:57

标签: angular kendo-ui kendo-ui-angular2

In this plunk我正在尝试将焦点放在kendo-window的第一个字段上(单击按钮以打开窗口)。我用ViewChild声明了该字段,但是当窗口打开时它是undefined,因为程序启动时尚未创建该窗口。

当我尝试设置焦点时,我得到Cannot read property 'nativeElement' of undefined(请参见控制台)。

创建窗口后,是否可以用ViewChild引用变量?打开窗口时如何在第一个字段上设置焦点?

@Component({
  selector: 'my-app',
  template: `
    <div class="example-wrapper">
    <button kendoButton (click)="open()">Open window</button>
    <kendo-window title="Some title" *ngIf="opened" (close)="close()" [width]="450">

        <form class="k-form">
            <input kendoTextBox type="text" name="userId" placeholder="User ID"
                 #userId class="k-textbox" autofocus>
            <input kendoTextBox type="text" name="firstName" placeholder="First Name" 
                 #firstName class="k-textbox">
        </form>

        </kendo-window>
      </div>
    `
})
export class AppComponent {
    public opened = false;

    @ViewChild('userId') uid: ElementRef;

    open(){
      this.opened = true;
      this.uid.nativeElement.focus();
    }

    close(){
      this.opened = false;
    }

}

更新

更改了PLUNK,以显示第二次打开窗口时autofocus不起作用。

2 个答案:

答案 0 :(得分:1)

我将弹出窗口放入其自己的组件中。然后,我尝试在该组件focus()中调用ngOnInit(),但仍然遇到问题。用零毫秒将其包装到setTimeout中似乎已经解决了。我只需像您一样绑定模板变量,然后在ngOnInit

中调用它
@ViewChild('userId') userId: ElementRef;

public ngOnInit() {
    setTimeout(() => {
      this.userId.nativeElement.select();
    }, 0)
  }

这里是Stackblitz

答案 1 :(得分:0)

应该足以在元素上设置自动对焦。

相关问题