繁体   English   中英

将输入字段集中在值更改上? 角2

[英]focus input field on value change? angular2

我有一个输入字段,可在modalOpen = true时添加活动类,并且此方法工作正常。

但是,当此模式显示时,我希望它专注于输入字段吗?

 <div [class.active]="modalOpen">
     <input>
 </div>

将本地模板变量添加到输入元素: <input #input1> ,并使用@ViewChild('input1') input1ElementRef;对其进行引用@ViewChild('input1') input1ElementRef;

然后,无论将modalOpen设置为true modalOpen ,也this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', [])使用this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', [])设置对输入元素this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', [])
使用Renderer是网络工作者的安全。

import {Component, ViewChild, Renderer} from 'angular2/core';

@Component({
  selector: 'my-comp',
  template: `<div [class.active]="modalOpen">
       <input #input1>
     </div>
     <button (click)="showModal()">show modal</button>`
})
export class MyComponent {
  @ViewChild('input1') input1ElementRef;
  modalOpen = false;
  constructor(private _renderer:Renderer) {}
  showModal() {
    this.modalOpen = true;
    // give Angular a chance to create or show the modal
    setTimeout( _ => 
      this._renderer.invokeElementMethod(
        this.input1ElementRef.nativeElement, 'focus', []);
    );
  }
}

@Component({
  selector: 'my-app',
  template: `<my-comp></my-comp>`,
  directives: [MyComponent]
})
export class AppComponent {
  constructor() { console.clear(); }
}

矮人

我有一个示例组件,当一个元素变为“活动”状态时,我将焦点放在该组件上。 这是我的方法:

export class Spreadsheet implements AfterViewChecked{

    ngAfterViewChecked(){
        //some logic to find "active" element 
        let cell = document.getElementById(this.model.current.rowIndex + '-' + this.model.current.columnIndex);
        cell.focus();
    }
}

此处更多信息: http : //www.syntaxsuccess.com/viewarticle/virtualized-spreadsheet-component-in-angular-2.0

http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

<input type="text" #myInput />
{{ myInput.focus() }}

只需在模板内部输入后添加{{myInput.focus()}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM