2016-01-13 56 views
1

我有一个输入字段,当modalOpen = true时,它会添加活动类,并且这个工作正常。关注价值变化的投入领域? angular2

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

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

貌似http://stackoverflow.com/questions/34522306/angular-2-focus-on-newly-added-input-element –

回答

1

我在哪里设置当元件涉及“活性”集中的样品组分。 这里是我的方法:

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

5

本地模板变量添加到您的输入元素:<input #input1>,并得到一个参考使用它来@ViewChild('input1') input1ElementRef;

然后,无论你在哪里设置modalOpentrue,还可以将焦点集中在this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', [])的输入元素上。
使用渲染器是Web工作者的安全。

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

+0

感谢的DUP!我一直在寻找这个 - 我想单击按钮时关注输入。 – Drusantia