如果允许我这样做,我将参与@Sasxa 答案的一部分并对其进行修改,使其更像您正在寻找的内容。
一些变化
- 我将使用一个
ngFor
所以 angular2 添加新的输入而不是我自己做。主要目的只是让 angular2 对其进行迭代。
- 代替
ViewChild
我要使用ViewChildren
返回一个查询列表 https://github.com/angular/angular/blob/master/modules/angular2/src/core/linker/query_list.ts其中有一个changes https://github.com/angular/angular/blob/master/modules/angular2/src/core/linker/query_list.ts#L34财产。该属性是一个 Observable,它会返回更改后的元素。
由于在 ES5 中,我们没有装饰器,因此我们必须使用queries
使用的财产ViewChildren
成分
Component({
selector: 'cmp',
template : `
<div>
// We use a variable so we can query the items with it
<input #input (keydown)="add($event)" *ngFor="#input of inputs">
</div>
`,
queries : {
vc : new ng.core.ViewChildren('input')
}
})
Focus在最后一个元素上。
ngAfterViewInit: function() {
this.vc.changes.subscribe(elements => {
elements.last.nativeElement.focus();
});
}
正如我之前所说,ViewChildren 返回一个 QueryList,其中包含changes
财产。当我们订阅它时,每次它发生变化时,它都会返回元素列表。列表elements
包含一个last
属性(除其他外)在本例中返回最后一个元素,我们使用nativeElement
最后focus()
添加输入元素这纯粹是为了方便,输入数组除了重绘之外没有任何真正的目的ngFor
.
add: function(key) {
if(key.which == 13) {
// See plnkr for "this.inputs" usage
this.inputs.push(this.inputs.length+1);
}
}
我们推一个dummy数组上的项目,因此它会重绘。
使用 ES5 的示例:http://plnkr.co/edit/DvtkfiTjmACVhn5tHGex http://plnkr.co/edit/DvtkfiTjmACVhn5tHGex
使用 ES6/TS 的示例:http://plnkr.co/edit/93TgbzfPCTxwvgQru2d0?p=preview http://plnkr.co/edit/93TgbzfPCTxwvgQru2d0?p=preview
更新 29/03/2016
时间已经过去,事情已经澄清,并且总是有最佳实践可以学习/教授。我通过改变一些事情简化了这个答案
- 而不是使用
@ViewChildren
并订阅它我制作了一个指令,每次创建新输入时都会实例化该指令
- 我在用着
Renderer
确保 WebWorker 安全。原始答案访问focus()
直接在nativeElement
这是不鼓励的。
- 现在我听
keydown.enter
这简化了按键事件,我不必检查which
value.
说到点子上了。该组件看起来像(下面的 plnkrs 上的简化完整代码)
@Component({
template: `<input (keydown.enter)="add()" *ngFor="#input of inputs">`,
})
add() {
this.inputs.push(this.inputs.length+1);
}
和指令
@Directive({
selector : 'input'
})
class MyInput {
constructor(public renderer: Renderer, public elementRef: ElementRef) {}
ngOnInit() {
this.renderer.invokeElementMethod(
this.elementRef.nativeElement, 'focus', []);
}
}
正如你所看到的,我正在打电话invokeElementMethod
引起focus
在元素上而不是直接访问它。
这个版本比原来的版本更干净、更安全。
plnkrs 更新至 beta 12
使用 ES5 的示例:http://plnkr.co/edit/EpoJvff8KtwXRnXZJ4Rr http://plnkr.co/edit/EpoJvff8KtwXRnXZJ4Rr
使用 ES6/TS 的示例:http://plnkr.co/edit/em18uMUxD84Z3CK53RRe http://plnkr.co/edit/em18uMUxD84Z3CK53RRe
2018年更新
invokeElementMethod
已弃用。使用 Renderer2 而不是 Renderer。
给你的元素一个id,你就可以使用选择根元素 https://angular.io/api/core/Renderer2#selectRootElement:
this.renderer2.selectRootElement('#myInput').focus();