【发布时间】:2019-04-30 17:39:38
【问题描述】:
当我们通过箭头键继续选项并按空格键 (32) 选择 mat-option 时,如何填充 mat-chip onkeypress(spacebar)。
但是,当我们通过箭头键选择下拉菜单然后按回车键(keycode-13)但在空格键(keycode-32)上没有类似的工作时,它工作正常。
这里是 stackblitz 链接:- https://stackblitz.com/edit/angular-ytk8qk-feaqaw?file=app/chips-autocomplete-example.html
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
2)How to remove option from dropdown that is already populated or used.
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
Note:- The user can create chips by typing in input and then press ENTER or SPACE key (separator key) for creating chips.
chip.component.ts
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
separatorKeysCodes: number[] = [ENTER,SPACE, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string[]>;
fruits: string[] = ['Lemon'];
allFruits: string[] = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}
}
【问题讨论】:
-
似乎如果列表组件被聚焦,空格键的作用与回车相同。在您提供的 stackblitz 上,我尝试检查列表中的一个元素,然后返回列表,按空格键并被选中。也许知道这一点可以帮助您实现您正在寻找的东西。
-
它不工作。您不必使用鼠标打开下拉菜单。当输入为焦点时,只需使用箭头键选择特定选项,然后单击空格键选择该选项。但是,输入键正在工作。
-
您查看过这个吗?空间似乎不是自动完成的选项material.angular.io/components/autocomplete/…
-
谢谢,键盘交互 DOWN_ARROW:下一个选项变为活动状态。UP_ARROW:上一个选项变为活动状态。ENTER:选择当前活动项目。
-
但是,也可以使用空格键选择。这是要求
标签: angular typescript angular-material angular7