問題描述
如何使用按鍵角 9 選擇下拉值 (how to select the dropdown value using key press angular 9)
目前的場景是這樣一個下拉菜單包含多個選項。
value: Values[] = [
{ value: '1', viewValue: '1' },
{ value: '2', viewValue: '2' },
{ value: '3', viewValue: '3' }
];`
<select formControlName="item">
<option *ngFor="let i of foods" [value]="i.value">{{i.value}}</option>
</select>
要求是如果我點擊鍵盤上的1,那麼需要選擇選項1。我試過使用 @HostListener('window:keydown', ['$event']) 但沒有奏效。有沒有可以用的例子。?如何使用鍵盤輸入選擇選項??
監聽器的示例代碼如下。
@HostListener('window:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.keypressed = event.keyCode;
console.log('this.keypressed', this.keypressed)
}
關閉下拉菜單時可以使用。如果下拉菜單打開,則 this.keypressed 的值不會被填充
參考解法
方法 1:
For a simple matSelect, you can use the (keydown)
event mixed with an [(ngModel)]
to do it :
import {
Component,
} from "@angular/core";
import { MatSelect } from "@angular/material/select";
interface Food {
value: string;
viewValue: string;
}
/**
@title Basic select
*/
@Component({
selector: "select‑overview‑example",
templateUrl: "select‑overview‑example.html",
styleUrls: ["select‑overview‑example.css"]
})
export class SelectOverviewExample {
foods: Food[] = [
{ value: "steak‑0", viewValue: "Steak" },
{ value: "pizza‑1", viewValue: "Pizza" },
{ value: "tacos‑2", viewValue: "Tacos" }
];
firstSelect = this.foods[2].value;
onKeyPressed(event: KeyboardEvent, mySelect: MatSelect) {
if (event.keyCode ‑ 97 >= 0 && event.keyCode ‑ 97 <= 2) {
this.firstSelect = this.foods[event.keyCode ‑ 97].value;
mySelect.close();
}
}
}
</code></pre>
<h4>Basic mat‑select</h4>
<mat‑form‑field appearance="fill">
<mat‑label>Favorite food</mat‑label>
<mat‑select #mySelect [(ngModel)]="firstSelect" (keydown)="onKeyPressed($event, mySelect)">
<mat‑option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat‑option>
</mat‑select>
</mat‑form‑field>
Here is the repro on Stackblitz.
The select must be focused of course, either by a mouse click or by tabulation on the keyboard.
97 is the ASCII code of the number 1
in the ASCII table.
I tried doing it with a formControl
but could not achieve to update the selected value in the html. If you know how to do it then you could use it if you need it in a form.
(by Manu Mohanan、Quentin Grisel)
參考文件