一种获取使用以下命令创建的元素的引用的方法*ngFor
is @ViewChildren()
如果元素实际上是组件或指令,则可以将组件/指令类型作为参数传递,否则可以添加模板变量,并且可以使用模板变量的名称(作为字符串)来查询元素。
在这种情况下,模板变量和组件类型都返回组件实例,但要调用焦点,我们需要ElementRef.nativeElement
因此我创建了一个应用于的辅助指令ion-input
用于查询元素并调用focus()
:
import {Component, Directive, Renderer, HostListener, ViewChildren, ElementRef} from 'angular2/core'
/// Helper directive
@Directive({
selector: 'ion-input'
})
class Focusable {
constructor(public renderer: Renderer, public elementRef: ElementRef) {}
focus() {
console.debug(this.elementRef.nativeElement);
this.renderer.invokeElementMethod(
this.elementRef.nativeElement, 'focus', []);
}
}
/// Test component instead of the original ion-input
@Component({
selector: 'ion-input',
host: {'tabindex': '1'},
template: `
<div>input (focused: {{focused}})</div>
`,
})
export class IonInput {
focused:boolean = false;
@HostListener('focus')
focus() {
this.focused = true;
}
@HostListener('blur')
blur() {
this.focused = false;
}
}
/// Queries the elements and calls focus
@Component({
selector: 'my-app',
directives: [IonInput, Focusable],
template: `
<h1>Hello</h1>
<div *ngFor="let product of products">
<ion-input #input type="text"></ion-input>
</div>
<button *ngFor="let product of products; let index=index" (click)="setFocus(index)">set focus</button>
`,
})
export class AppComponent {
constructor(private renderer:Renderer) {
console.debug(this.renderer)
}
products = ['a', 'b', 'c']
@ViewChildren(Focusable) inputs;
ngAfterViewInit() {
// `inputs` is now initialized
// iterate the elements to find the desired one
}
setFocus(index) {
// `inputs` is now initialized
// iterate the elements to find the desired one
//var input = ...
//console.debug(this.inputs.toArray()[1]);
this.inputs.toArray()[index].focus();
}
}
也可以看看Angular 2:关注新添加的输入元素 https://stackoverflow.com/questions/34522306/angular-2-focus-on-newly-added-input-element
笨蛋的例子 https://plnkr.co/edit/JUMdao?p=preview