打开 Kendo Window 时在文本框中设置焦点
Setting focus in text box when Kendo Window is opened
In this plunk 我正在尝试将焦点设置在 kendo-window
打开时的第一个字段(单击按钮打开 window)。我用 ViewChild
声明了该字段,但是当 window 打开时它是 undefined
,因为当程序启动时 window 尚未创建。
当我尝试设置焦点时,我得到 Cannot read property 'nativeElement' of undefined
(请参阅控制台)。
是否可以在创建window后用ViewChild
引用一个变量? window打开时如何设置焦点在第一个字段?
@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
在第二次打开 window 时不起作用。
应该足以在元素上设置自动对焦。
我将弹出窗口放入其自己的组件中。然后我尝试在该组件 ngOnInit()
中调用 focus()
但仍然遇到您的问题。将它包装成零毫秒的 setTimeout
似乎已经解决了它。我只是像你一样绑定模板变量并在 ngOnInit
中调用它
@ViewChild('userId') userId: ElementRef;
public ngOnInit() {
setTimeout(() => {
this.userId.nativeElement.select();
}, 0)
}
这是一个Stackblitz
In this plunk 我正在尝试将焦点设置在 kendo-window
打开时的第一个字段(单击按钮打开 window)。我用 ViewChild
声明了该字段,但是当 window 打开时它是 undefined
,因为当程序启动时 window 尚未创建。
当我尝试设置焦点时,我得到 Cannot read property 'nativeElement' of undefined
(请参阅控制台)。
是否可以在创建window后用ViewChild
引用一个变量? window打开时如何设置焦点在第一个字段?
@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
在第二次打开 window 时不起作用。
应该足以在元素上设置自动对焦。
我将弹出窗口放入其自己的组件中。然后我尝试在该组件 ngOnInit()
中调用 focus()
但仍然遇到您的问题。将它包装成零毫秒的 setTimeout
似乎已经解决了它。我只是像你一样绑定模板变量并在 ngOnInit
@ViewChild('userId') userId: ElementRef;
public ngOnInit() {
setTimeout(() => {
this.userId.nativeElement.select();
}, 0)
}
这是一个Stackblitz