【问题标题】:Setting focus in text box when Kendo Window is opened打开剑道窗口时在文本框中设置焦点
【发布时间】:2018-07-27 14:53:57
【问题描述】:

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 在第二次打开窗口时不起作用。

【问题讨论】:

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


    【解决方案1】:

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

    @ViewChild('userId') userId: ElementRef;
    
    public ngOnInit() {
        setTimeout(() => {
          this.userId.nativeElement.select();
        }, 0)
      }
    

    这是Stackblitz

    【讨论】:

    • 我想你忘了把 setTimeout 添加到你的 Stackblitz 中,我添加了它,它运行良好。
    • 是的,它似乎没有保存最后一个状态。我更新了堆栈闪电战。很高兴它有帮助:)
    • 我唯一的问题是我将变量声明为#userId="ngModel" 而不是简单的#userId,在这种情况下我得到一个异常Cannot read property 'select' of undefined 因为userId 被创建为@987654332 @object 而不是ElementRefnativeElementngModel 中不存在,有什么想法吗?我使用ngModel 向该字段添加验证。
    • 我找到了解决方案:我声明了两个元素 #userId="ngModel"#focusMe
    【解决方案2】:

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

    【讨论】:

    • 这对我不起作用,如果窗口被 ngIf 第二次打开,则焦点未设置。
    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多