问题
I have this a bunch of input fields which are created dynamically
<tr *ngFor="let row of rows; let rowIdx = index">
<td *ngFor="let col of columns; let colIdx = index">
<mat-form-field class="example-full-width">
<input #inputs #test type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"
(keyup.enter)="shiftFocusEnter(rowIdx, colIdx)">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</td>
</tr>
I want to get access to these input fields in my classes. I'm currently using
@ViewChild('test', { read: MatAutocompleteTrigger }) test: MatAutocompleteTrigger;
to access it. However this will only give me the first input field of all the ones which have been created through the loop.
Using ViewChildren instead only results in Errors while calling intern functions of the "test" object
e.g.
this.test.closePanel() => "this.test.closePanel is not a function"
Edit1:
To provide more info, I have a dynamically created table (rows and columns). My table is currently filled with multiple input fields. I can tab through these input fields by pressing the enter key.
However if i tab by pressing the enter key, the suggestion panel of the angular autocomplete material will not close. Thats why I try to call the closePanel() method manually however by using this approach described above, only the first cell is "recognized" hence the closePanel() method only works on the first cell - input element
EDIT 2:
I managed to solve this a couple of weeks ago but forgot to update in case someone has this problem as well.
This is how my method looks like right now:
shiftFocusEnter(rowIdx: number, colIdx: number) {
console.log("Enter", rowIdx, colIdx);
if(colIdx == 4 && rowIdx == 5) {
console.log("Reached end of row");
}
else {
colIdx = colIdx + this.columns.findIndex(c => c.editable);
this.focusInput(rowIdx, colIdx);
this.autocompletes.toArray().forEach(el => {
el.closePanel();
})
}
}
focusInput(rowIdx: number, colIdx: number) {
console.log("FOCUS ON", rowIdx, colIdx);
let inputEls = this.inputs.toArray();
let flatIdx = (rowIdx * this.columns.length) + colIdx;
inputEls[flatIdx].nativeElement.focus();
}
来源:https://stackoverflow.com/questions/48404155/get-reference-of-multiple-elements