我希望在“激活”后重点关注我的输入。 原因是我正在构建一个多步骤表单(如this one),它有多个输入,我将逐一显示。 这就是我的尝试。
@Component(
...
template: `<input *ngIf="myCondition" id="myId" (load)="myLoad()">`){
myCondition = false;
load(){
document.getElementById("myId").focus();
}
}
当myCondition稍后变为true时,不会触发(load)事件,在我看来,在这种情况下,它似乎是最合乎逻辑的DOM事件。
someFunction(){
this.myCondition = true;
document.getElementById("myId").focus();
}
如果尚未加载输入元素,则失败:document.getElementById(“myId”)返回undefined
。如果我setTimeOut
它像100ms这样的东西它确实有效,但它不是一个非常优雅的解决方案,理想的超时在不同的客户端会有所不同。
关于在DOM中加载输入时如何实现输入焦点的任何其他想法?
答案 0 :(得分:3)
终于找到了解决问题的方法。我制作了一个名为 focus 的指令来处理当前的输入。
工作演示:http://plnkr.co/edit/TzQNL6DcIJ9tjAntu6Si?p=preview
@Directive({
selector:'[focus]',
})
export class focusDirective{
constructor(private el:ElementRef, private rd:Renderer){
console.log(this.el.nativeElement);
rd.setElementStyle(el.nativeElement,'background','yellow');
}
ngAfterViewInit(){
this.el.nativeElement.focus();
}
}
<强> Component.ts 强>
@Component({
selector: 'my-app',
directives:[focusDirective],
template: `
<div *ngIf="step==1">
#{{step}}step :<input focus type="text">
</div>
<div *ngIf="step==2">
#{{step}}step : <input focus type="text">
</div>
<div *ngIf="step==3">
#{{step}}step : <input focus type="text">
</div>
<hr>
<button (click)="next()">NEXT</button>
`
})
export class App {
step=1;
next(){
++this.step;
}
}
答案 1 :(得分:0)
对于动态创建的输入(即在表格中),可以使用@ViewChildren
更改监听器完成
模板:
<tr *ngFor="let row of rows">
<td>
<input type="text" #name>
</td>
</tr>
组件
@Component({
selector: 'my-component',
templateUrl: './my-componentt.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit, AfterViewInit {
@ViewChildren('name') nameInputs: QueryList<ElementRef>
ngAfterViewInit(): void {
this.nameInputs.changes.subscribe(()=>{
setTimeout(()=>{
this.nameInputs.last.nativeElement.focus()
});
})
}
}