关注价值变化的输入领域? angular2

时间:2016-01-13 01:07:18

标签: angular

我有一个输入字段,当modalOpen = true时添加类激活,这样可以正常工作。

但是,我想让它在这个模态显示时专注于输入字段?

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

3 个答案:

答案 0 :(得分:5)

将一个本地模板变量添加到您的输入元素:<input #input1>,并使用@ViewChild('input1') input1ElementRef;获取对它的引用。

然后,无论您将modalOpen设置为true,还可以使用this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', [])将焦点设置在输入元素上。
使用Renderer是Web worker的安全。

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(); }
}

plunker

答案 1 :(得分:1)

我有一个示例组件,当元素出现时,我会设置焦点&#34;活动&#34;。 这是我的方法:

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

答案 2 :(得分:0)

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

在模板中输入后立即添加 {{myInput.focus()}}