In this plunk I'm trying to set the focus on the first field of a kendo-window
when it is opened (click on the button to open the window). I declared the field with ViewChild
, however it's undefined
when the window is opened as when the program starts the window hasn't been created yet.
When I attempt to set the focus, I get Cannot read property 'nativeElement' of undefined
(see the console).
Is it possible to reference a variable with ViewChild
after the window is created? How to set the focus on the first field when the window is opened?
@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;
}
}
UPDATE
Changed the PLUNK to show that autofocus
does not work the second time the window is opened.
I put the popup into its own component. I then tried to call focus()
in that components ngOnInit()
but still had your problem. Wrapping it into a setTimeout
with zero ms seemed to have solved it. I simply bind the template variable like you did and call this in the ngOnInit
@ViewChild('userId') userId: ElementRef;
public ngOnInit() {
setTimeout(() => {
this.userId.nativeElement.select();
}, 0)
}
Here is a Stackblitz