在这个沉重的我试图在打开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;
}
}更新
更改按钮以显示第二次打开窗口时autofocus无法工作。
发布于 2018-07-28 20:07:24
我把弹出框放进了它自己的组件里。然后,我试图在组件focus()中调用ngOnInit(),但仍然遇到了问题。把它封装成一个零毫秒的setTimeout似乎解决了这个问题。我只是像您所做的那样绑定模板变量,并在ngOnInit中调用它
@ViewChild('userId') userId: ElementRef;
public ngOnInit() {
setTimeout(() => {
this.userId.nativeElement.select();
}, 0)
}这是一个斯塔克布利茨
发布于 2018-07-28 00:27:18
应该在元素上设置自动聚焦。
https://stackoverflow.com/questions/51560567
复制相似问题