我目前正在制作一个表格,用户可以通过按Enter键来浏览可编辑元素 . 我也在这里使用Angular Material .
我有一个mat-form-field,带有几个动态创建的输入字段和mat-autocomplete元素 . 但是我的回车键事件在这方面有点不同 .
当您按下输入字段时,将打开一个面板(下拉列表),用户可以在其中选择输入,或者他可以简单地自己编写,面板将提供建议(自动完成) .
What happens if you press the tab key?
如果在键入时按Tab键,光标将移动到下一个可编辑元素,并且最新元素的面板(下拉列表)将关闭 .
What happens if you press the enter key
如果在键入时按Enter键,光标将移动到下一个可编辑元素但是最新元素的面板(下拉列表)保持打开状态,这导致多个输入字段具有打开的下拉面板,即使用户已经写了他需要的内容至 .
模板:
<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 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>
这只是根据数组中对象的数量创建行(这里不太重要) .
输入字段上还有一个keyup.enter事件,当用户按下输入时会触发,同时焦点位于输入字段上,并传递行索引和列索引以获取下一个可编辑元素 .
零件:
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.autocomplete.showPanel = false;
this.focusInput(rowIdx, colIdx);
}
}
该函数接收两个参数 . 行索引和列索引,并计算要关注的下一个可编辑元素的索引 .
编写 this.autocomplete.showPanel = false 行是为了看看我是否可以像这样关闭面板,但它没有用 .
this.autocomplete 是类 MatAutocomplete 的对象 . 我通过写作添加了这个
@Input('matAutocomplete')
autocomplete: MatAutocomplete
What I need:
我想按下回车键后,自动完成元素的下拉面板关闭 .
提前致谢!
Update:
所以在工作了一下后我发现了这个
@ViewChild('test', { read: MatAutocompleteTrigger }) test: MatAutocompleteTrigger;
this.test.closePanel();
这次我可以关闭表中FIRST单元的面板,但是其他输入字段的所有面板都将保持打开状态
2 回答
我的用例略有不同,因此您的更新对我不起作用,但我发现了一个稍微不同的解决方案:
然后您可以使用它来关闭下拉选项:
确保还导入ViewChild:
奇迹般有效 .
这个comment提供了一个解决方案,您可以直接在输入元素上获得对 matAutocompleteTrigger 的引用,以便您可以在模板中调用closePanel() . 例如: