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

Angular 打开剑道窗口时在文本框中设置焦点,angular,kendo-ui,kendo-ui-angular2,Angular,Kendo Ui,Kendo Ui Angular2,我试图将焦点设置在剑道窗口打开时的第一个字段上(单击按钮打开窗口)。我用ViewChild声明了该字段,但是当窗口打开时它是未定义的,就像程序启动时窗口还没有创建一样 当我试图设置焦点时,我得到无法读取未定义的属性“nativeElement”(请参阅控制台) 创建窗口后,是否可以使用ViewChild引用变量?当窗口打开时,如何在第一个字段上设置焦点 @Component({ selector: 'my-app', template: ` <div class="exam

我试图将焦点设置在
剑道窗口打开时的第一个字段上(单击按钮打开窗口)。我用
ViewChild
声明了该字段,但是当窗口打开时它是
未定义的
,就像程序启动时窗口还没有创建一样

当我试图设置焦点时,我得到
无法读取未定义的属性“nativeElement”(请参阅控制台)

创建窗口后,是否可以使用
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;
    }

}
@组件({
选择器:“我的应用程序”,
模板:`
开窗
`
})
导出类AppComponent{
公开=假;
@ViewChild('userId')uid:ElementRef;
开(){
this.opened=true;
this.uid.nativeElement.focus();
}
关闭(){
this.opened=false;
}
}
更新


更改了PLUNK以显示第二次打开窗口时自动对焦不起作用。

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

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

@ViewChild('userId') userId: ElementRef;

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

这是一个对我不起作用的

,如果窗口是用NGI隐藏的,如果第二次打开窗口,焦点没有设置。我想你忘了将
设置超时
添加到Stackblitz,我添加了它,它工作得很好。是的,它似乎没有保存上一个状态。我更新了stackblitz。很高兴它有帮助:)我唯一的问题是我将变量声明为
#userId=“ngModel”
,而不是简单的
#userId
,在这种情况下,我得到一个异常
无法读取未定义的属性“select”,因为
用户ID
被创建为
ngModel
对象,而不是
ElementRef
nativeElement
ngModel
中不存在,有什么想法吗?我使用
ngModel
向字段添加验证。我找到了一个解决方案:我声明了两个元素
\userId=“ngModel”
\focusMe