Ein Ansatz Referenzen von Elementen mit *ngFor
ist @ViewChildren()
erstellt bekommen, wenn die Elemente tatsächlich Komponenten oder Richtlinien sind dann die Komponente/directive Typ kann als Parameter sonst ein Template-Variable übergeben werden kann hinzugefügt werden und der Namen Die Template-Variable (als String) kann verwendet werden, um die Elemente abzufragen.
In diesem Fall sowohl ein Template-Variable und der Komponententyp die Komponenteninstanz zurück, sondern Fokus anrufen müssen wir die ElementRef.nativeElement
deshalb ich eine Helfer-Richtlinie erstellt, die ion-input
angewandt wird, und verwendet wird, um die Elemente abzufragen und auch focus()
anrufen :
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();
}
}
Siehe auch Angular 2: Focus on newly added input element
Plunker example
Wurde Ihr Problem lösen? –